Skip to content

Instantly share code, notes, and snippets.

@kwoncharles
Last active December 26, 2020 08:23
Show Gist options
  • Save kwoncharles/277a433e6a13d57cd3ec2cd08069f726 to your computer and use it in GitHub Desktop.
Save kwoncharles/277a433e6a13d57cd3ec2cd08069f726 to your computer and use it in GitHub Desktop.
compound components Tab
// Tabs.jsx
import React from 'react'
const TabContext = React.createContext()
function Tabs({ children }) {
const [selectedTab, setTab] = React.useState(initialTab)
return (
<TabContext.Provider value={{ selectedTab, setTab }}>
<ul className="tab-container">
{children}
</ul>
</TabContext.Provider>
)
}
Tabs.Item = ({ value, children }) => {
const ctx = React.useContext(TabContext)
if (ctx === undefined) {
throw new Error('<Tabs.Item> 컴포넌트는 <Tabs> 컴포넌트 아래에서만 사용될 수 있습니다.')
}
const { selectedTab, setTab } = ctx
return (
<li
onClick={() => setTab(value)}
className={`tab-item ${selectedTab === value ? 'selected' : ''}`}
>
{children}
</li>
)
}
// Page.jsx
function Page() {
return (
<Tabs>
{/* 원하는 대로 children을 구성할 수 있습니다. */}
<BetweenComponent>
{tabItems.map(tabItem => (
<Tabs.Item value={tabItem}>
{tabItem}
</Tabs.Item>
))}
</BetweenComponent>
</Tabs>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment