Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass value from parent component to child component (react)

I'm new to learning React, and am trying to pass on a value that I'm getting from user input inside of my ParentComponent (via input box) into its ChildComponent - which I'll use the user input value to run an AJAX call.

I thought that by replacing the state in the ParentComponent would work - but I'm still not able to grab it in the ChildComponent.

I also only want the ChildComponent to run/render only after receiving the input value from the ParentComponent (so that I can run the AJAX call and then render...).

Any tips?

var ParentComponent = React.createClass({
     getInitialState: function() {
         return {data: []};
     },

    handleSearch: function(event) {
        event.preventDefault();
        var userInput = $('#userInput').val();
        this.replaceState({data: userInput});
    },

    render: function() {
        return (
            <div>
                <form>
                    <input type="text" id="userInput"></input>
                    <button onClick={this.handleSearch}>Search</button>
                </form>
                <ChildComponent />
                {this.props.children}
            </div>
          );
        }
    });

var ChildComponent = React.createClass({
   render: function() {
        return <div> User's Input: {this.state.data} </div>
       }
   });
like image 797
codinginnewyork Avatar asked Oct 31 '15 22:10

codinginnewyork


1 Answers

You should pass parent state as a prop to your child: Change your childcomponent inside parent render to:

<ChildComponent foo={this.state.data} />

And then you can access it inside ChildComponent through this.props.foo.

Explanation: Inside ChildComponent, this.state.someData refers to ChildComponent state. And your child doesn't have state. (Which is fine by the way)

Also: this.setState() is probably better than this.replaceState().

And better to initialize parent state with

return { data : null };
like image 166
wintvelt Avatar answered Nov 05 '22 01:11

wintvelt