-
Context 생성
import React, { createContext, useState, useContext } from 'react';
const TabsContext = createContext();
const useTabs = () => useContext(TabsContext);
const TabsProvider = ({ children }) => {
const [activeTab, setActiveTab] = useState(0);
const switchTab = (tabIndex) => {
setActiveTab(tabIndex);
};
return (
<TabsContext.Provider value={{ activeTab, switchTab }}>
{children}
</TabsContext.Provider>
);
};
export { TabsProvider, useTabs };
-
Tabs 컴포넌트 생성
const Tabs = ({ children }) => {
return (
<TabsProvider>
{children}
</TabsProvider>
);
};
const TabList = ({ children }) => {
return <div>{children}</div>;
};
const Tab = ({ children, index }) => {
const { activeTab, switchTab } = useTabs();
return (
<button onClick={() => switchTab(index)}
style={{ fontWeight: index === activeTab ? 'bold' : 'normal' }}>
{children}
</button>
);
};
const TabPanels = ({ children }) => {
return <div>{children}</div>;
};
const TabPanel = ({ children, index }) => {
const { activeTab } = useTabs();
if (index !== activeTab) return null;
return <div>{children}</div>;
};
Tabs.TabList = TabList;
Tabs.Tab = Tab;
Tabs.TabPanels = TabPanels;
Tabs.TabPanel = TabPanel;
export default Tabs;
-
Tabs 컴포넌트 사용
const App = () => {
return (
<Tabs>
<Tabs.TabList>
<Tabs.Tab index={0}>Tab 1</Tabs.Tab>
<Tabs.Tab index={1}>Tab 2</Tabs.Tab>
<Tabs.Tab index={2}>Tab 3</Tabs.Tab>
</Tabs.TabList>
<Tabs.TabPanels>
<Tabs.TabPanel index={0}>Content of Tab Panel 1</Tabs.TabPanel>
<Tabs.TabPanel index={1}>Content of Tab Panel 2</Tabs.TabPanel>
<Tabs.TabPanel index={2}>Content of Tab Panel 3</Tabs.TabPanel>
</Tabs.TabPanels>
</Tabs>
);
};