Reputation:
I'm rank new to React thus the question.
I have a parent component that has a button
. This is my code,
class MyPage extends React.Component{
constructor(props){
super(props);
this.state = { messages: []};
this.onRefreshClick = this.onRefreshClick.bind(this);
}
componentWillMount() {
......
}
onRefreshClick(){
event.preventDefault();
console.log("Refresh clicked !!!");
fetchMessages(fetch_url + "/" + this.state.user.id).then((res) => {
this.setState({messages: res});
console.log(this.state.messages);
});//end of outer promise
}
render(){
return(
<div>
<div className="col-md-2 left-pane">
<div className="col-md-2 header-left-block">
<button className="btn refresh-btn" onClick={this.onRefreshClick} type="submit">Refresh</button>
</div>
</div>
<div className="col-md-8 middle-pane">
<ReceivedImages />
</div>
</div>
);
}
}
The messages object is getting populated by the method onRefreshClick when the Refresh button is clicked on the parent.
I want to pass this data to the child component, <ReceivedImages />
as props and load them when the button is clicked on the parent. How do I do this.
It is easy to simulate this behavior if the refresh button was inside the <ReceivedImages />
component by using a call back, but how do I do it in this case?
Upvotes: 1
Views: 126
Reputation: 42460
You can simply pass the parent's state down to the children as props. When the parent's state is updated, the render()
function will be executed and the children's props will be updated automatically, triggering a re-render of them in turn.
<ReceivedImages messages={this.state.messages} />
They will be available in the the child component as this.props.messages
.
Upvotes: 2