개발

< React > custom Hook 만들기 #2

Hanagertudekim 2022. 6. 24. 11:24
  • < useTabs >
    • 버튼 2개를 만들어서 각 버튼마다 다른 내용이 뜨게 만들고싶은 컨셉
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"
  }
];

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>
  );
};

export default App;

 

  • const idx = useTabs ( );
    • idx.currentItem → allTabs[currentIndex]
    • idx.changeItem → setCurrentIndex

'개발' 카테고리의 다른 글

< html > vs code에서 유용한 html 자동완성  (0) 2022.06.24
<html> herf, src, url 차이점  (0) 2022.06.24
< React > react 에서 Event 다루기  (0) 2022.06.24
< React > Router 정리  (1) 2022.06.24
< React > custom Hooks 만들기 #1  (0) 2022.06.24