Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re render parent component when anything changes in Child Component? [closed]

Tags:

reactjs

**Hi,

How to re render parent component when anything changes in Child Component?**

Thanks,

like image 212
Santraj Kumar Avatar asked Nov 23 '18 06:11

Santraj Kumar


1 Answers

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.

like image 58
Shawn Andrews Avatar answered Sep 18 '22 09:09

Shawn Andrews