Last active
July 19, 2021 07:40
-
-
Save isabellachen/7abc397d6785d668fdd081aa7e51e6c3 to your computer and use it in GitHub Desktop.
React.useContext() in action
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 | |
// http://localhost:3000/isolated/exercise/03.js | |
import * as React from 'react' | |
import {Switch} from '../switch' | |
/** | |
* Create a Toggle component that accepts child elements and shares its | |
* state with its child elements. This example shows a good use case for | |
* React.useContext() to expose your component's state management API | |
* to users so they don't need to worry about state management. | |
*/ | |
const ToggleContext = React.createContext(); | |
ToggleContext.displayName = 'ToggleContext' //Nice name for chrome debugger tools | |
function Toggle({children, ...props}) { | |
const [on, setOn] = React.useState(false) | |
const toggle = () => setOn(!on) | |
const value = {on, toggle} | |
return ( | |
<ToggleContext.Provider value={value} {...props}> | |
{children} | |
</ToggleContext.Provider> | |
) | |
} | |
function useToggle() { | |
const context = React.useContext(ToggleContext) | |
if (!context) { | |
throw new Error('useToggle() must be used within the context provider') | |
} | |
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 right?</ToggleOn> | |
<ToggleOff>The button is off</ToggleOff> | |
<div> | |
<ToggleButton /> | |
</div> | |
</Toggle> | |
</div> | |
) | |
} | |
export default App | |
/* | |
eslint | |
no-unused-vars: "off", | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment