Reputation: 171
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 Child from './Child';
class Parent extends Component {
rerender=()=>{
this.forceUpdate()
}
render() {
return (
<div>
<p className='animate-left'>Animation</p>
<Child rerender={this.rerender}/>
</div>
);
}
}
export default Parent;
here is the Child component:
import React, { Component } from 'react';
class Child extends Component {
clickHandler=()=>{
this.props.rerender()
}
render() {
return (
<div>
<button onClick={this.clickHandler}>Click</button>
</div>
);
}
}
export default Child;
i want to animate again/ re-render parent component by clicking the button of child component. How to do that?
Upvotes: 1
Views: 4793
Reputation: 4217
You have to have state
in the parent component and pass down this state to the child component:
import React, { Component } from "react";
import Child from "./Child";
class Parent extends Component {
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>
<p className="animate-left" key={this.state.counter}>Animation</p>
<Child rerender={this.rerender} />
</div>
);
}
}
export default Parent;
and in the child component update this state:
import React, { Component } from "react";
class Child extends Component {
clickHandler = () => {
this.props.rerender();
};
render() {
return (
<div>
<button onClick={this.clickHandler}>Click</button>
</div>
);
}
}
export default Child;
Upvotes: 2