[hooks] useTabs

HYl·2022년 4월 12일
1

React Hooks

목록 보기
2/4

버튼에 따라 노출되는 내용을 변화시킬 수 있는 custom hook인 useTabs 에 대해여 정리해 볼 것이다.


const content = [
  {
    tab: "Section 1",
    content: "This is the content of the Section 1"
  },
  {
    tab: "Section 2",
    content: "This is the content of the Section 2"
  }
];

우선, tab을 클릭할 때 나타낼 content 배열 객체 형태로 정의하였다.

useTabs

useTabs는 initialTab, allTabs 두 개의 매개 변수를 갖고 currentItem 과 changeItem 을 return 하는 형식으로 구성되어있다.

  • initialTab : 초기에 노출할 content index
  • allTabs : 모든 content

useTabs에서 setCurrentIndex라는 함수를 오브젝트 안에 넣어서 리턴해준다.
그래서 Home에서 useTabs만 호출해 놓으면 changeItem를 이용하여 setCurrentIndex을 이용할 수 있다.
따라서, Home에서 onChange를 따로 만들지 않고도 button의 onClick에서 현재의 index만 인자 값으로 넘기면 content가 변환이 되는 것이다.

// useTabs hook
const useTabs = (initialTab, allTabs) => {
  if (!allTabs || !Array.isArray(allTabs)) {
    return
  }
  const [currentIndex, setCurrentIndex] = useState(initialTab)

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

const Home = () => {
  const { currentItem, changeItem } = useTabs(0, content)
  
  return (
    <div>
      {content.map((section, index) => (
        <button onClick={() => changeItem(index)}>{section.tab}</button>
      ))}
      <div>{currentItem.content}</div>
    </div>
  )
}

export default Home

Error 처리

위에서 정의한 useTabs를 사용할 때 두 번째 매개변수를 주지 않거나(!allTabs), 두번째 매개변수가 배열이 아니라면(!Array.isArray(allTabs)) return 처리를 해주어서 Error가 발생하지 않게 처리를 하였다.

  • Array.isArray() 메서드는 인자가 Array인지 판별한다.
const useTabs = (initialTab, allTabs) => {
  if (!allTabs || !Array.isArray(allTabs)) { 
    return; 
  }
  
  const [currentIndex, setCurrentIndex] = useState(initialTab);
  
  return {
    currentItem: allTabs[currentIndex],
    changeItem: setCurrentIndex
  };
};

결과물


REFERENCE

profile
꾸준히 새로운 것을 알아가는 것을 좋아합니다.

0개의 댓글