Skip to content

Instantly share code, notes, and snippets.

@mqklin
Created February 21, 2019 01:53
Show Gist options
  • Save mqklin/273bccbddc48b3bc0d120fa97257a26e to your computer and use it in GitHub Desktop.
Save mqklin/273bccbddc48b3bc0d120fa97257a26e to your computer and use it in GitHub Desktop.
Class remover
import React, {memo, useContext} from 'react';
const Context = React.createContext();
export function withContext(Component, keys) {
Component = memo(Component);
return memo(function(props) {
let state = useContext(Context);
if (process.env.NODE_ENV !== 'production') {
keys.forEach(key => {
if (props.hasOwnProperty(key) && state.hasOwnProperty(key)) {
console.error(`Dublicate in props and context value, name '${key}'`); // eslint-disable-line no-console
}
if (!state.hasOwnProperty(key)) {
console.error(`There is no '${key}' in the context`); // eslint-disable-line no-console
}
});
state = keys.reduce(
(acc, field) => {
acc[field] = state[field];
return acc;
},
{},
);
}
return (
<Component
{...state}
{...props}
/>
);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment