Compound Tabs Components
ReactJS
Hard
7 views
Problem Description
Build simple compound tabs: Tabs, Tabs.List, Tabs.Panel.
Output Format
Render a React component.
Constraints
Use context to share active tab id.
Official Solution
import React, { createContext, useContext, useMemo, useState } from 'react';
const TabsContext = createContext(null);
function Tabs({ defaultValue, children }) {
const [value, setValue] = useState(defaultValue);
const ctx = useMemo(() => ({ value, setValue }), [value]);
return <TabsContext.Provider value={ctx}>{children}</TabsContext.Provider>;
}
function List({ children }) {
return <div style={{ display: 'flex', gap: 10 }}>{children}</div>;
}
function Tab({ value, children }) {
const ctx = useContext(TabsContext);
const active = ctx.value === value;
return (
<button
type='button'
onClick={() => ctx.setValue(value)}
style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: active ? '#0b5' : '#fff', color: active ? '#fff' : '#124' }}
>
{children}
</button>
);
}
function Panel({ value, children }) {
const ctx = useContext(TabsContext);
if (ctx.value !== value) return null;
return <div style={{ marginTop: 12, border: '1px solid #eee', borderRadius: 14, padding: 12 }}>{children}</div>;
}
Tabs.List = List;
Tabs.Tab = Tab;
Tabs.Panel = Panel;
export default function App() {
return (
<div style={{ padding: 16, width: 420 }}>
<Tabs defaultValue='topics'>
<Tabs.List>
<Tabs.Tab value='topics'>Topics</Tabs.Tab>
<Tabs.Tab value='practice'>Practice</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value='topics'>Browse topics on meetcode.</Tabs.Panel>
<Tabs.Panel value='practice'>Solve one question now.</Tabs.Panel>
</Tabs>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!