Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do React forceUpdate() to a child component?

I can force reload for a parent component with this.forceUpdate(), but how to do it for a child component?

i.e. following react class methods:

buttonClick = () => {
   //This updates parent (this) component
   this.forceUpdate(); 

  //This causes runtime error ("..not a function in buttonClick...")
   Rtable.forceUpdate();
}

render () {
  <div>
     <RTable />
  </div>
}
like image 860
Kaj Risberg Avatar asked Jun 04 '20 09:06

Kaj Risberg


2 Answers

If child component is not memoized then rendering its parent will render the child.

If child component is memoized, you could force update with its reference.

And of course, passing different properties to a child, changing its state, will re-render it.

Changing the key will UNMOUNT the component, it is like making a conditional rendering on it.

Here is an example demonstating everything mentioned:

class Child extends React.Component {
  componentDidMount() {
    console.log("mounted");
  }
  render() {
    console.log("rendered");
    return <div>Child</div>;
  }
}

class App extends React.Component {
  state = {
    counter: 0
  };

  childRef = React.createRef();
  onClick = () => this.forceUpdate();
  onCounter = () => this.setState({ counter: this.state.counter + 1 });
  onRef = () => this.childRef.current.forceUpdate();

  render() {
    return (
      <>
        <Child key={this.state.counter} ref={this.childRef} />
        <button onClick={this.onClick}>Render</button>
        <button onClick={this.onCounter}>Update Key</button>
        <button onClick={this.onRef}>Render with ref</button>
      </>
    );
  }
}

Edit lucid-hill-vfvr3

like image 116
Dennis Vash Avatar answered Oct 05 '22 13:10

Dennis Vash


<RTable key={some variable that changes between renders} />

As pointed out below this will cause unmount, which causes the child to lose its state and also run componentWillUnmount, componentDidMount and constructor methods (which may be useful when you want to resubscribe).

Documentation https://reactjs.org/docs/glossary.html#keys

like image 33
rdkn Avatar answered Oct 05 '22 11:10

rdkn