Last active
June 22, 2021 12:05
-
-
Save intrnl/519a3dbfee37611fa9c0b619654c0cbb to your computer and use it in GitHub Desktop.
React tabination 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
import React from 'react'; | |
////// Core component | |
/// <Tabination /> | |
let TabinationContext = React.createContext(null); | |
export function Tabination (props) { | |
let { children } = props; | |
let [current, setCurrent] = React.useState(); | |
return ( | |
<TabinationContext.Provider value={[current, setCurrent]}> | |
{children} | |
</TabinationContext.Provider> | |
); | |
} | |
/// useTabination | |
export function useTabination () { | |
return React.useContext(TabinationContext); | |
} | |
////// Presentational component | |
/// <Tab /> | |
export function Tab (props) { | |
let { id, children } = props; | |
let [current, setCurrent] = useTabination(); | |
return ( | |
<button onClick={() => setCurrent(id)}> | |
{children} | |
</button> | |
); | |
} | |
/// <Page /> | |
export function Page (props) { | |
let { id, children } = props; | |
let [current, setCurrent] = useTabination(); | |
return ( | |
current === id && ( | |
children | |
) | |
); | |
} | |
////// Example usage | |
function App () { | |
return ( | |
<Tabination> | |
<div> | |
<Tab id='foo'> | |
Foo | |
</Tab> | |
<Tab id='bar'> | |
Bar | |
</Tab> | |
</div> | |
<Page id='foo'> | |
Foo | |
</Page> | |
<Page id='bar'> | |
Bar | |
</Page> | |
</Tabination> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment