Validate Compound Component Context Consumers

Share this video with your friends

Send Tweet

If someone uses one of our compound components outside the React.createContext <ToggleContext.Provider />, they will experience a confusing error. We could provide a default value for our context, but in our situation that doesn't make sense. Instead let's build a simple function component which does validation of our contextValue that comes from the <ToggleContext.Consumer />. That way we can provide a more helpful error message.

flowstate
flowstate
~ 6 years ago

I'm sorry for asking something off-topic, but: could you possibly share how you set up some of the convenience functionality / hotkeys you show during this lecture? In this video, you chose a single ToggleContext.Consumer node, then selected all the matching tags, and renamed them all. In a video earlier you did some quick tricks (possibly just good editing?) to surround an arrow function's code with parentheses. I'm new to JS in IDEs, and am looking for any way to increase my productivity.

On topic, thanks for the exceptionally clear and useful videos.

Kent C. Dodds
Kent C. Dodds(instructor)
~ 6 years ago

Hi flowstate, Maybe sometime I'll make that the subject of a devtip. I'm glad you like it :)

Nazariy
Nazariy
~ 5 years ago

props.children is a function? How come we can call it with the context?

Rafal Pastuszak
Rafal Pastuszak
~ 5 years ago

@Nazariy props.children can be either and array of children or a single item. In this case props.children is a function, e.g.: { contextValue => (contextValue.on ? children : null) }

Given:

<div className='parent'>
  <div className='child' />
</div>

parent's props.children will be <div className='child' /> not [ <div className='child' /> ]