React Custom Component -Tab

임성은·2022년 12월 23일

오류해결


이번엔 오류해결까지 같이 적어야한다.

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

이 오류는 onClick={ selectMenuHandler(index)} 이 함수때문에 생긴 것이다.
렌더 과정에서 state를 변화하는 함수가 있다면 리랜더링이 계속 일어나면서 발생하는 에러이다.

이 문제는 onClick={()=> {selectMenuHandler(index)}}

화살표함수로 바꿔주면 해결된다^^


import { useState } from 'react';
import styled from 'styled-components';

// TODO: Styled-Component 라이브러리를 활용해 TabMenu 와 Desc 컴포넌트의 CSS를 구현합니다.

const TabMenu = styled.ul`
  background-color: #dcdcdc;
  color: rgba(73, 73, 73, 0.5);
  font-weight: bold;
  display: flex;
  flex-direction: row;
  justify-items: center;
  align-items: center;
  list-style: none;
  margin-bottom: 7rem;

  .submenu {
    ${'' /* 기본 Tabmenu 에 대한 CSS를 구현합니다. */}
    margin: 10px;
    display: flex;
    justify-content: space-around;
    width: 100px;
   
  }

  .focused {
    ${'' /* 선택된 Tabmenu 에만 적용되는 CSS를 구현합니다.  */}
    background-color: blue;
    
    
  }

  & div.desc {
    text-align: center;
  }
`;

const Desc = styled.div`
  text-align: center;
`;

export const Tab = () => {
  // TIP: Tab Menu 중 현재 어떤 Tab이 선택되어 있는지 확인하기 위한
  // currentTab 상태와 currentTab을 갱신하는 함수가 존재해야 하고, 초기값은 0 입니다. //OK
 const [currentTab, setCurrentTab] = useState(0);

  const menuArr = [
    { name: 'Tab1', content: 'Tab menu ONE' },
    { name: 'Tab2', content: 'Tab menu TWO' },
    { name: 'Tab3', content: 'Tab menu THREE' },
  ];

  const selectMenuHandler = (index) => {
    // TIP: parameter로 현재 선택한 인덱스 값을 전달해야 하며, 이벤트 객체(event)는 쓰지 않습니다
    // TODO : 해당 함수가 실행되면 현재 선택된 Tab Menu 가 갱신되도록 함수를 완성하세요.
    setCurrentTab(index)
  };

  return (
    <>
      <div>
        <TabMenu>
          {/*TODO: 아래 하드코딩된 내용 대신에, map을 이용한 반복으로 코드를 수정합니다.*/}
          {/*TIP: li 엘리먼트의 class명의 경우 선택된 tab 은 'submenu focused' 가 되며, 
                  나머지 2개의 tab은 'submenu' 가 됩니다.*/}
          {menuArr.map((tab,index) => {
            return(
              <li key={index} className={currentTab === index ? 'submenu focused':'submenu'}
              onClick={()=> {selectMenuHandler(index)}}
              >{tab.name} </li>
            )
          })} 
          
        </TabMenu>
        <Desc>
          {/*TODO: 아래 하드코딩된 내용 대신에, 현재 선택된 메뉴 따른 content를 표시하세요
          TypeError: Cannot read properties of undefined (reading 'content')오류가뜸. 테스트는 ok*/}
          <p>{menuArr[currentTab].content}</p>
        </Desc>
      </div>
    </>
  );
};

profile
개발자의 길에 당차게 들어서다!!

0개의 댓글