Last active
June 1, 2018 00:26
-
-
Save marcelmokos/67727bf494cf11ddf435b2c9675c09f1 to your computer and use it in GitHub Desktop.
React optionally controlled components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow | |
const deriveStateFromProps = (nextProps: Object, prevState: Object) => { | |
const derivedStateUpdate: Object = Object.keys(nextProps).reduce( | |
(acc, key) => { | |
if (nextProps[key] !== undefined && nextProps[key] !== prevState[key]) { | |
return { ...acc, [key]: nextProps[key] }; | |
} | |
return acc; | |
}, | |
{}, | |
); | |
if (Object.keys(derivedStateUpdate).length === 0) { | |
return null; | |
} | |
return derivedStateUpdate; | |
}; | |
class Component extends React.Component { | |
static getDerivedStateFromProps(nextProps: Props, prevState: State) { | |
return deriveStateFromProps(nextProps, prevState); | |
} | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment