[React] CustomHook ๐Ÿ‘‰ useTabs

7987 ๋‹จ์–ด ReacthookReact

https://nomadcoders.co ์—์„œ ๊ฐ•์˜๋ฅผ ๋“ฃ๊ณ  ์ •๋ฆฌํ•œ ๋‚ด์šฉ ์ž…๋‹ˆ๋‹ค.

1. useTabs ์ด๋ž€

  • button tab ์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค!

2. useTabs ์ž‘์„ฑํ•˜๊ธฐ

const useTabs = (initialTab, allTabs) => {
  const [currentIndex, setCurrentIndex] = useState(initialTab);

  // function ์‹œ์ž‘ํ•  ๋•Œ ์—๋Ÿฌ ํ™•์ธ
  if (!allTabs || !Array.isArray(allTabs)) {
    return;
  }

  // index
  return {
    currentItem: allTabs[currentIndex],
    changeItem: setCurrentIndex
  }
}

3. useTabs ์‚ฌ์šฉํ•˜๊ธฐ

  • ๋จผ์ € ๊ฐ€์ ธ์˜ฌ ๋ฐ์ดํ„ฐ๋ฅผ ๋งŒ๋“ค์–ด์ค€๋‹ค.
    • api๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๋“ฑ์œผ๋กœ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค!
const content = [
  {
    tab: "section 1",
    content: "section1์˜ content"
  },

  {
    tab: "section 2",
    content: "section2์˜ content"
  },

  {
    tab: "section 3",
    content: "section3์˜ content"
  }
]
  • ๋ฐ์ดํ„ฐ ๋ณด์—ฌ์ฃผ๊ธฐ
const App = () => {
  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>
  ) 
}

4. ์—๋Ÿฌ ๋ฐœ์ƒ..


Each child in a list should have a unique "key" prop.
์ด์™€ ๊ฐ™์€ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.
key ๊ฐ’์ด ์—†์–ด์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋˜ ๊ฒƒ...

<button onClick={() => changeItem(index)} key={index}> {section.tab} </button>

key={index} ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๊ฒฐํ–ˆ๋‹ค!!!

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ