Created
February 21, 2019 01:53
-
-
Save mqklin/273bccbddc48b3bc0d120fa97257a26e to your computer and use it in GitHub Desktop.
Class remover
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
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