The getDerivedStateFromProps()
method is where we can set the state object based on the initial props. It takes the state
as an argument and returns an object with changes to the state
. It is called just before rendering the element in the DOM.
static getDerivedStateFromProps(props, state) {
return {newState: props };
}
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {fullName: "Billy Brown"};
}
static getDerivedStateFromProps(props, state) {
return {fullName: props.name + "Doe" };
}
render() {
return (
<h1>My full name is {this.state.fullName}</h1>
);
}
}
Passing props:
<Example name={"John"} />
Here, we can see getDerivedStateFromProps()
modifies the value initiated in the constructor and replaces with the one defined at the getDerivedStateFromProps()
method.