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>
}
});
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 };
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