728x90
반응형
useTabs
버튼에 따라 노출되는 내용을 변화시킬 수 있는 custom hook
useTabs 사용 예시
import React, { useState } from "react";
import ReactDOM from "react-dom";
const content = [
{
tab: "Secton 1",
content: "I'm the content of the Section 1"
},
{
tab: "Secton 2",
content: "I'm the content of the Section 2"
},
];
const useTabs = (initialTab, allTabs) => {
if(!allTabs || Array.isArray(allTabs)) {
return;
}
const [currentIndex, setCurrentIndex] = useState(initialTab);
return {
currentItem: allTabs[currentIndex],
changeItem: setCurrentIndex
};
};
const App = () => {
const {currentItem, changeItem} = useTabs(0, content);
return (
<div className="App">
{content.map((section, index) => (
<button onClick={() => changeItem(index)}>{section.tab}</button>
))}
<div>{currentItem.content}</div>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM render(<App />, rootElement);
반응형
'프로그래밍 > React' 카테고리의 다른 글
[React] React Hooks (4.1) - useEffect 활용법 (0) | 2023.01.30 |
---|---|
[React] useEffect (0) | 2023.01.27 |
[React] React Hooks (2) - useInput (0) | 2023.01.25 |
[React] React Hooks (1) - useState (0) | 2023.01.20 |
[React] Hooks란? (0) | 2023.01.19 |