Skip to content

Instantly share code, notes, and snippets.

@drbr
Last active December 16, 2020 01:39
Show Gist options
  • Save drbr/c45213b990ffd149d733d3f6d00261e0 to your computer and use it in GitHub Desktop.
Save drbr/c45213b990ffd149d733d3f6d00261e0 to your computer and use it in GitHub Desktop.
React HOC to render a wrapped component with a given key
/**
* Higher Order Component that renders the wrapped component with the given key (derived from its
* props), which allows us to easily "reset" a component if certain props change.
* @param component
* @param getKey
*/
export function KeyOn<P>(component: React.ComponentType<P>, getKey: (props: P) => string) {
const displayName = `KeyOn(${component.displayName})`;
const hoc = (props: P) => {
const key = getKey(props);
return React.createElement(component, { ...props, key });
};
hoc.displayName = displayName;
return hoc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment