Skip to content

Instantly share code, notes, and snippets.

@Twipped
Created May 16, 2024 19:18
Show Gist options
  • Save Twipped/99c4cdb293c202b1f8c8c2b1d56cdfa2 to your computer and use it in GitHub Desktop.
Save Twipped/99c4cdb293c202b1f8c8c2b1d56cdfa2 to your computer and use it in GitHub Desktop.
This code works, but it's really badly written. Find everything wrong with it.
import {
createContext,
useContext,
forwardRef,
Children,
useState,
} from "react";
const TabContext = createContext();
/**
*
* @param props
* @param props.children
*/
function Tabs({ children, onChange, value }) {
const [activeId, setActiveId] = useState(value);
const currentTab = Children.toArray(children).find(
(child) => child.props.id === activeId
);
const changeTab = (value) => {
setActiveId(value);
onChange(value);
};
return (
<>
<TabContext.Provider value={{ activeId, changeTab }}>
<div style={{ display: "flex" }}>{children}</div>
</TabContext.Provider>
{currentTab.props.children}
</>
);
}
var Tab = forwardRef(({ label, id, ...props }) => {
const { activeId, changeTab } = useContext(TabContext);
const selected = activeId === id;
return (
<a
style={{
padding: "5px",
borderStyle: selected ? "inset" : "outset",
cursor: "pointer",
}}
onClick={() => changeTab(id)}
{...props}
>
{label}
</a>
);
});
export default function App() {
return (
<Tabs onChange={console.log} value="apple">
<Tab label="Apple" id="apple">
<img src="https://thisinspired.life/wp-content/uploads/2019/12/Reine_des_Reinette-300x300.jpg" />
</Tab>
<Tab label="Pear" id="pear">
<img
height="500"
src="https://cdn.shopify.com/s/files/1/0059/8835/2052/files/Kieffer_pear_5_FGT_8e20f03c-c1b8-4474-b089-71af5b086aaa.jpg"
/>
</Tab>
<Tab label="Orange" id="orange">
<img
height="500"
src="https://www.allrecipes.com/thmb/y_uvjwXWAuD6T0RxaS19jFvZyFU=/1500x0/filters:no_upscale():max_bytes(150000):strip_icc()/GettyImages-1205638014-2000-d0fbf9170f2d43eeb046f56eec65319c.jpg"
/>
</Tab>
</Tabs>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment