Sylar Sylar - 3 months ago 8
HTML Question

Shorter way to push child props data to parent

Is there a shorter, more cleaner way to push data from child props to parent?

var Parent = React.createClass({

_result: function(data){
console.log(data);
},

render: function(){
return(<Child bar={this._result} />)
}

});

var Child = React.createClass({

_foo: function(e){
this.props.bar(e.target.value);
},

render: function(){
return(
<div>
<input type="text" onChange={this._foo} />
</div>
)
}

});


Could
onChange
be simplified without having a
_foo()
function? I only need to push the input's value to the parent function
_result()
.

Answer

You can get rid of the _foo function, and just assign the passed function to onChange. You'd have to adjust the _result function a bit though, since onChange will pass the event as argument. Here's an example:

var Parent = React.createClass({

  _result: function(e) {
    console.log(e.target.value);
  },

  render: function() {
    return(<Child bar={this._result} />)
  }

});

var Child = React.createClass({

  render: function() {
    return(
      <div>
        <input type="text" onChange={this.props.bar}
      </div>
    )
  }

});