Skip to content Skip to sidebar Skip to footer

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:

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;

Post a Comment for "How To Re-render Parent Component From Child Component"