Created
July 9, 2021 04:53
-
-
Save ronnycoding/7316f6607599ac29902e953ce688db7d to your computer and use it in GitHub Desktop.
Flexible Compound Components with context
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
// Flexible Compound Components with context | |
// 💯 custom hook validation | |
import * as React from 'react' | |
import {Switch} from '../switch' | |
const ToggleContext = React.createContext() | |
ToggleContext.displayName = 'ToggleContext' | |
function Toggle({children}) { | |
const [on, setOn] = React.useState(false) | |
const toggle = () => setOn(!on) | |
return ( | |
<ToggleContext.Provider value={{on, toggle}}> | |
{children} | |
</ToggleContext.Provider> | |
) | |
} | |
function useToggle() { | |
const context = React.useContext(ToggleContext) | |
if (context === undefined) { | |
throw new Error('useToggle must be used within a <Toggle />') | |
} | |
return context | |
} | |
function ToggleOn({children}) { | |
const {on} = useToggle() | |
return on ? children : null | |
} | |
function ToggleOff({children}) { | |
const {on} = useToggle() | |
return on ? null : children | |
} | |
function ToggleButton({...props}) { | |
const {on, toggle} = useToggle() | |
return <Switch on={on} onClick={toggle} {...props} /> | |
} | |
function App() { | |
return ( | |
<div> | |
<Toggle> | |
<ToggleOn>The button is on</ToggleOn> | |
<ToggleOff>The button is off</ToggleOff> | |
<div> | |
<ToggleButton /> | |
</div> | |
</Toggle> | |
</div> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment