**Hi,
How to re render parent component when anything changes in Child Component?**
Thanks,
To rerender the parent you have a couple options: you can change parent's state(triggering an update) or you can forcibly trigger an update. Either way the update will trigger a rerender.
Below is a demonstration of forcibly rerendering the parent using the this.forceUpdate()
function.
// Example class component
class Child extends React.Component {
constructor(props) {
super(props);
this.onBtnClick = this.onBtnClick.bind(this);
this.state = {
value: 0
};
}
onBtnClick() {
this.setState({ value: this.state.value + 1 });
this.props.rerenderParentCallback();
}
render() {
console.log(`Child rendered.`);
return (
<div>
<span>Im the child with value {this.state.value}</span>
<button onClick={() => { this.onBtnClick(); }}>Click to increment child</button>
</div>
);
}
}
// Example class component
class Parent extends React.Component {
constructor(props) {
super(props);
this.rerenderParentCallback = this.rerenderParentCallback.bind(this);
}
rerenderParentCallback() {
this.forceUpdate();
}
render() {
console.log(`Parent rendered.`);
return (
<div>
<div>Im the parent</div>
<Child rerenderParentCallback={this.rerenderParentCallback}/>
</div>
);
}
}
// Render it
ReactDOM.render(
<Parent/>,
document.getElementById("react")
);
button {
margin: 10px;
}
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Also you'll see that if you comment out the line this.props.rerenderParentCallback();
then only the child will be rerendered.
If you want to rerender the parent without using forceUpdate() then you could do something as simple as toggling a boolean in the parent's state via this.setState({ toggleRerender: !this.state.toggleRerender })
in the rerenderParentCallback
function.
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