I have a bit of a dilemma with React getDerivedStateFromProps
lifecycle methods. Following is an example and you can find a working codesandbox here. What I want to do is change the child state from parent (Turn Off From Parent) some times.
import React, { Component } from "react";
import { render } from "react-dom";
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
isOn: true
};
this.turnOff = this.turnOff.bind(this);
}
turnOff(event) {
event.preventDefault();
this.setState({
isOn: false
});
}
render() {
return (
<div>
<Child isOn={this.state.isOn} />
<p>
<a href="#" onClick={this.turnOff}>
Turn Off From Parent
</a>
</p>
</div>
);
}
}
class Child extends Component {
constructor(props) {
super(props);
this.state = {
isOn: false
};
this.turnOff = this.turnOff.bind(this);
this.turnOn = this.turnOn.bind(this);
}
turnOff(event) {
event.preventDefault();
this.setState({
isOn: false
});
}
turnOn(event) {
event.preventDefault();
this.setState({
isOn: true
});
}
static getDerivedStateFromProps(props, state) {
if (props.isOn) {
return { ...state, isOn: true };
}
return null;
}
render() {
const toggleState = this.state.isOn ? "ON" : "OFF";
return (
<div>
<p>I am {toggleState}</p>
<p>
<a href="#" onClick={this.turnOn}>
Turn On From Child
</a>{" "}
|{" "}
<a href="#" onClick={this.turnOff}>
Turn Off From Child
</a>
</p>
</div>
);
}
}
render(<Parent />, document.getElementById("app"));
I did read You Probably Don't Need Derived State. However I was wondering if there is a way to solve this without Fully controlled component or Fully uncontrolled component with a key because the only problem here is getDerivedStateFromProps
triggers everytime when the local state change, unlike componentWillReceiveProps
which runs when the parent component renders the child component.