-
-
Save samuel-gomez/389e2809a7934e30d2dcb6ab09fa984d to your computer and use it in GitHub Desktop.
create react context that has a validated consumer.
This file contains hidden or 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
| // 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