본문 바로가기

react

[react] useTabs

import "./styles.css";
import { useState } from "react";
import React from "react";

function App() {
  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) => {
    const [currentIndex, setCurrentIndex] = useState(initialTab);
    return {
      currentItem: allTabs[currentIndex],
      changeItem: setCurrentIndex
    }
  }

  const {currentItem, changeItem} = useTabs(0, content);

  return (
    <div className="App">
      <div>
        {content.map((section, index) => (
          <button onClick={() => changeItem(index)}>{section.tab}</button>
        ))}
      </div>
      <div>
        {currentItem.content}
      </div>
    </div>
  );
}

export default App;

'react' 카테고리의 다른 글

[react] useConfirm  (0) 2022.12.11
[react] useClick  (0) 2022.12.11
[react] useInput  (0) 2022.12.09
[react] useRef()  (0) 2022.12.07
[react] react-router-dom 설치, 형식  (0) 2022.12.04