Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Created May 15, 2018 22:31
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save kentcdodds/5156fd21595e227819a4d2011fe51822 to your computer and use it in GitHub Desktop.
Save kentcdodds/5156fd21595e227819a4d2011fe51822 to your computer and use it in GitHub Desktop.
create react context that has a validated consumer.
// create a React context Provider/Consumer pair that
// validates the consumer is rendered within a provider
function createRequiredContext(name) {
const Context = React.createContext()
function Consumer(props) {
return (
<Context.Consumer {...props}>
{val => {
if (!val) {
throw new Error(
`The ${name}Consumer must be rendered ` +
`within a ${name}Provider and it was not`
)
}
return props.children(val)
}}
</Context.Consumer>
)
}
return { Provider: Context.Provider, Consumer }
}
// const LanguageContext = createRequiredContext('Language')
// ReactDOM.render(<LanguageContext.Consumer />, rootEl)
// ERROR: The LanguageConsumer must be rendered within a
// LanguageProvider and it was not
//
// @kentcdodds <3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment