Skip to content

Instantly share code, notes, and snippets.

@marcelmokos
Last active June 1, 2018 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcelmokos/67727bf494cf11ddf435b2c9675c09f1 to your computer and use it in GitHub Desktop.
Save marcelmokos/67727bf494cf11ddf435b2c9675c09f1 to your computer and use it in GitHub Desktop.
React optionally controlled components
// @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