Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing props to parent in React JS

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>
        )
    }
})
like image 793
user3053089 Avatar asked Dec 15 '22 15:12

user3053089


1 Answers

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.

like image 67
argentum47 Avatar answered Jan 01 '23 14:01

argentum47