Updating Child Component Using Parent's State
Show an example where the parent's state change leads to updated props in the child component, triggering a re-render.
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
message: 'Hello from Parent!'
};
}
// Method to change the state of the Parent Component
updateMessage = (newMessage) => {
this.setState({ message: newMessage });
};
render() {
return (
<div>
<h1>Parent</h1>
{/* Child component receives message from parent's state as a prop */}
<ChildComponent message={this.state.message} />
{/* Button to change parent state and hence update Child component */}
<button onClick={() => this.updateMessage('Updated message from Parent!')}>Update Message</button>
</div>
);
}
}
This is the ParentComponent class which contains a state 'message'. It passes this state as a prop to the ChildComponent. It also has an 'updateMessage' method to update its own state.
class ChildComponent extends React.Component {
render() {
return (
<div>
<h2>Child</h2>
{/* Renders the message received from the parent component as a prop */}
<p>{this.props.message}</p>
</div>
);
}
}
This is the ChildComponent class which receives 'message' as a prop from the ParentComponent and renders it.