React JS: How to change props value from child component
As we know Props are immutable and we can pass them from Parent to child like below:
<ChildComponent myName={this.state.childMyName} />
in above code parent’s state myName now become props for child component ChildComponent.
here we can not change value of myName in child component as its coming form parent as a props and its immutable so how we can do that?
Here is solution.
We can write one callback function in child component like below:
<ChildComponent myName={this.state.childMyName} onChangeName={this.handleNameChange} />
In above line, we will write one callback method in child component where we will pass new name to parent.
The child would pass its requested new name as an argument to the event callback by calling, e.g., this.props.onChangeName('changed new name')
, and the parent would use the name in the event handler to update its state. Here child will call callback function onChangeName with new name and its get handled at parent like below. So this way parent will get new value of myName it will change it state and react will sent it to child with new value.
In Parent component:
handleNameChange = (changedNewNameFromchild) => { this.setState({ myName = changedNewNameFromchild }); }
Recent Comments