Skip to content

Instantly share code, notes, and snippets.

@asfktz
Last active November 23, 2019 11:19
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 asfktz/a76de98e92b5d2c045a1239b5b09da17 to your computer and use it in GitHub Desktop.
Save asfktz/a76de98e92b5d2c045a1239b5b09da17 to your computer and use it in GitHub Desktop.
Context Based Tabs
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} />;
}
@asfktz
Copy link
Author

asfktz commented Nov 23, 2019

Same Components as react-tabs and reach-tabs but with context

import { Tabs, TabList, Tab, TabPanels, TabPanel } from '../Tabs';

export const App = () => (
  <Tabs>
    <div className="header">
      <TabList>
          <Tab>aa</Tab>
          <Tab>bb</Tab>
        </TabList>
    </div>
    <div className="main">
      <TabPanels>
        <TabPanel>AA</TabPanel>
        <TabPanel>BB</TabPanel>
      </TabPanels>
    </div>
  </Tabs>
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment