Last active
November 23, 2019 11:19
-
-
Save asfktz/a76de98e92b5d2c045a1239b5b09da17 to your computer and use it in GitHub Desktop.
Context Based Tabs
This file contains hidden or 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, { Children, cloneElement, useState, createContext, useContext } from 'react'; | |
const ctx = createContext(); | |
export function Tabs ({ children }) { | |
const [selectedIndex, selectIndex] = useState(0); | |
return ( | |
<ctx.Provider value={{ selectedIndex, selectIndex }}> | |
{children} | |
</ctx.Provider> | |
); | |
} | |
export function TabList ({ children }) { | |
const { selectedIndex, selectIndex } = useContext(ctx); | |
return Children.map(children, (child, index) => ( | |
cloneElement(child, { | |
index: index, | |
isSelected: selectedIndex === index, | |
onSelect: () => selectIndex(index) | |
}) | |
)); | |
} | |
export function TabPanels (props) { | |
const { selectedIndex } = useContext(ctx); | |
const children = Children.toArray(props.children); | |
return children.find((child, index) => { | |
return index === selectedIndex; | |
}); | |
} | |
export function Tab ({ index, as: Comp = 'div', isSelected, onSelect, ...props }) { | |
return <Comp {...props} onClick={onSelect} /> | |
} | |
export function TabPanel ({ index, as: Comp = 'div', isSelected, ...props }) { | |
return <Comp {...props} />; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Same Components as react-tabs and reach-tabs but with context