How To Re-render Parent Component From Child Component
parent component has a p tag which animate it's inner text. animation works when i refresh the page. here is the Parent component: import React, { Component } from 'react'; import
Solution 1:
You have to have state
in the parent component and pass down this state to the child component:
importReact, { Component } from"react";
importChildfrom"./Child";
classParentextendsComponent {
constructor(props) {
super(props);
this.state = {
counter: 0
};
}
rerender = () => {
this.forceUpdate();
};
forceUpdate = () => {
this.setState((state) => ({
counter: state.counter + 1
}));
};
render() {
console.log("got rendered");
return (
<div><pclassName="animate-left"key={this.state.counter}>Animation</p><Childrerender={this.rerender} /></div>
);
}
}
exportdefaultParent;
and in the child component update this state:
importReact, { Component } from"react";
classChildextendsComponent {
clickHandler = () => {
this.props.rerender();
};
render() {
return (
<div><buttononClick={this.clickHandler}>Click</button></div>
);
}
}
exportdefaultChild;
Post a Comment for "How To Re-render Parent Component From Child Component"