Skip to content

Instantly share code, notes, and snippets.

@intrnl
Last active June 22, 2021 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrnl/519a3dbfee37611fa9c0b619654c0cbb to your computer and use it in GitHub Desktop.
Save intrnl/519a3dbfee37611fa9c0b619654c0cbb to your computer and use it in GitHub Desktop.
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