I would like to update all child components in an array using a prop passed down from the state of a parent component. A basic example is shown below. Each child component in the array is stateless and has a prop value which is determined by the state of the parent component. However, when the parent components state changes, the child components do not re-render with the change. How can I make the child components re-render when the parents state changes? Thanks!
import React from 'react';
import ReactDOM from 'react-dom';
class Child extends React.Component {
render(){
return (
<p>
<button onClick = {(e) => this.props.onClick(e)}>
click me
</button>
{this.props.test}
</p>
)
};
}
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {msg: 'hello', child_array: []};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e){
e.preventDefault();
const msg = this.state.msg == 'hello' ? 'bye' : 'hello';
this.setState({msg: msg});
}
componentDidMount(){
let store = [];
for (var i = 0; i < 5; i++){
store.push(<Child test = {this.state.msg} key = {i} onClick = {this.handleClick}/>);
}
this.setState({child_array: store});
}
render(){
return(
<div>
{this.state.child_array}
</div>
)
}
}
ReactDOM.render(<Parent />, document.getElementById('root'));