I want to create a Modal-like component that receives an open/closed boolean as a prop, then stores that value in the component state. When closing the Modal, I want to update the close boolean prop, but wait a few seconds before updating the component state so that I can add transition classes and animate the exit.
With componentWillReceiveProps
, I could accomplish this by wrapping this.setState
in a timeout and add the classes in the meantime. With the new React 16.3 API, I see that is is recommended to use the getDerivedStateFromProps
instead.
Since getDerivedStateFromProps
"should return an object to update state, or null to indicate that the new props do not require any state updates," (React docs) I want the method to look something like this:
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.menuIsOpen === false && prevState.menuIsOpen === true) {
return setTimeout(() => { menuIsOpen: false}, 1000);
}
return null;
}
But that doesn't work. I've read that setTimeout
does not return a value but am wondering if there is a more elegant solution to the problem than returning a promise.
You can use componentDidUpdate
:
componentDidUpdate(prevProps){
// update your class names...
if (!this.props.menuIsOpen && this.state.menuIsOpen) {
setTimeout(() => this.setState({ menuIsOpen: false}), 1000);
}
}
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