Java Scripts/React.js
Hook in React - useTabs
HobbyCoding
2023. 9. 28. 13:35
728x90
note) useTabs hook function은 currentItem data 와 setCurrentIndex 라는 modified 를 실어서 내보내고,
이것이 button 의 click event 에 mapping 되는 함수에서 index 이용하여 setCurrentIndex 를 호출되면서 currentItem.content 이 re-render 가 되는 구조이다.. 멋진 code 임.....
note) 아래 code 를 copy & paste 하여 실행하면 useTabs custom hook function 을 TEST 할 수 있다.
import { useState } from "react";
import "./styles.css";
const content = [
{
tab : "Section 1",
content : "I'm the content of the Section 1"
},
{
tab : "Section 2",
content : "I'm the content of the Section 2"
},
];
export const useTabs = (initialTab, allTabs) => {
if (!allTabs || !Array.isArray(allTabs)) {
return;
}
const [currentIndex, setCurrentIndex] = useState(initialTab);
return {
currentItem: allTabs[currentIndex],
changeItem: setCurrentIndex
};
};
export default function 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>
);
};
note) 위는 아래의 교육과장을 이수하면서 이해한 것들을 정리한 것이다.