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) 위는 아래의 교육과장을 이수하면서 이해한 것들을 정리한 것이다.
'Java Scripts > React.js' 카테고리의 다른 글
| Hook in React - useConfirm (0) | 2023.09.28 | 
|---|---|
| Hook in React - useHover (0) | 2023.09.28 | 
| Hook in React - useClick (0) | 2023.09.28 | 
| Hook in React - useTitle (0) | 2023.09.28 | 
| Hook in React - useInput (0) | 2023.09.28 |