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>
}
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>
</>
);
}
}
<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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With