Compound Components
Loading "Compound Components"
Run locally for transcripts
π¨βπΌ In this exercise we're going to make
<Toggle />
the parent of a few
compound components:<ToggleOn />
renders children when theon
state istrue
<ToggleOff />
renders children when theon
state isfalse
<ToggleButton />
renders the<Switch />
with theon
prop set to theon
state and theonClick
prop set totoggle
.
We have a Toggle component that manages the state, and we want to render
different parts of the UI however we want. We want control over the presentation
of the UI.
π¦ The fundamental challenge you face with an API like this is the state shared
between the components is implicit, meaning that the developer using your
component cannot actually see or interact with the state (
on
) or the
mechanisms for updating that state (toggle
) that are being shared between the
components.So in this exercise, we'll solve that problem by using the π
React Context API!
What we want to do in this exercise is allow users of our component to render
something when the toggle button is on and to render something else when that
toggle button is off without troubling them with managing the state that's
controlling whether it's shown or not.
Your job will be to make a
ToggleContext
which will be used to implicitly
share the state between these components. The Toggle
component will render the
ToggleContext
and the other compound components will access that
implicit state via use(ToggleContext)
.π¦Ί TypeScript might not like your
use
call depending on how you set up your
context. We'll deal with this in another step.