Last active
December 26, 2020 08:23
-
-
Save kwoncharles/277a433e6a13d57cd3ec2cd08069f726 to your computer and use it in GitHub Desktop.
compound components Tab
This file contains 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
// 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> | |
) | |
} |
This file contains 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
// 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