React-Hooks_ customHook (tab UI)

커스텀 훅 useTabs

import React, { useState } from "react";

const content = [
  {
    tab: "Section 1",
    content: "I'm the content 1"
  },
  {
    tab: "Section 2",
    content: "I'm the content 2"
  }
];

const useTabs = (initialTab, allTabs) => {
  if (!allTabs || !Array.isArray(allTabs)) {
    return;
  }
  const [currentIdx, setCurrentIdx] = useState(initialTab);
  return {
    currentItem: allTabs[currentIdx],
    changeItem: setCurrentIdx
  };
};

export const App = () => {
  const { currentItem, changeItem } = useTabs(0, content);
  // useTabs가 리턴하는 값
  return (
    <div className="App">
      <h1>Click Buttons!</h1>
      {content.map((sec, idx) => (
        <button onClick={() => changeItem(idx)}>{sec.tab}</button>
      ))}
      <div>{currentItem.content}</div>
    </div>
  );
};

좋은 웹페이지 즐겨찾기