Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React tabination context
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