Here I have a text field with a default number "3", and I want it to be updated when I input a value and click the button. Since, I'm updating the value in Child, I don't know how to pass props to Parent.
var Game = React.createClass({
getInitialState: function() {
return {
input: 3
};
},
setSize: function() {
//here it should update "input"
this.setState({input: /* value from Child */ })
},
render: function() {
return(
<div>
<div id='game'>
<Menu input={this.state.input}/>
</div>
</div>
)
}
});
var Menu = React.createClass({
render: function() {
return (
<div id='menu'>
<input type="number" id="myNumber" value={this.props.input}> </input>
<button id="mySetNumber" onclick={this.props.setSize}>Try it</button>
</div>
)
}
})
It can be like this:
var Game = React.createClass({
changeInput: function(e) {
this.setState({/* do something */})
},
render: function() {
return (
<div id="game">
<Menu onValueChange={this.changeInput} />
</div>
)
}
});
var Menu = React.createClass({
handleChange: function(e) {
this.props.onValueChange(/* pass the element or the value */)
}
render: function() {
return (
<div id="menu">
<input onChange={this.handleChange}/>
</div>
)
}
})
More or less something like this should work. For more see this. The idea is to pass a callback function from the parent to the child.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With