useTabs
import React, {useState} from "react";
import ReactDOM from "react-dom";
const content = [
{
tab: "Section1",
content: "I'm the content of the Section 1"
},
{
tab: "Section2",
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);
- 선택한 Section의 content만 보여줄 수 있음
- useState가 항상 initalTab을 갖음
- 배열의 인덱스가 0일때 첫번째 요소인 content[0]을 가져옴
- 기본적으로 allTabs의 인덱스는 0
- useTabs은 currentItem을 return 해주는 역할을 함
- 모든 버튼은 onClick 이벤트를 가짐
- 버튼은 클릭하면 index가 무엇이든지 상관없이 changeItem(index)를 실행
- changeItem의 index는 index안에 있는 값이 0또는 1로 변경
- setCurrentIndex의 item을 변경
- State를 변경해줌
- currentItem의 currentIndex를 변경하고 모든 것을 새로고침
- set state는 모든 걸 새로고침 해줌
- render function이 없다고 render가 안되는 것은 아님
공부 강의 : 노마더코더 - 실전형 리액트 Hooks 10개
'Front > React.js' 카테고리의 다른 글
[겨울방학-회사] react로 FAQ 리스트 만들기 : Accordion 구현 (0) | 2025.02.19 |
---|---|
Fetch API 란? (0) | 2025.02.12 |
useInput Hooks (0) | 2025.01.10 |
USESTATE Hooks (0) | 2025.01.09 |
리액트 Hooks (0) | 2025.01.08 |