본문 바로가기

Programming/React

[React]map 함수로 만든 메뉴에 개별 이벤트 걸기

728x90

- map으로 메뉴를 만들고 개별로 아코디언 메뉴 만들때 이벤트 걸어주기

 

import { useState } from "react";

const MenuArray = [
  {
    title:"메뉴1"
  },
  {
    title:"메뉴2"
  },
  {
    title:"메뉴3"
  },
  {
    title:"메뉴4"
  },
];

const Test = () => {
  const [activeIndex, setActiveIndex] = useState(-1);

  const handleToggleMenu = (index) => {
    setActiveIndex(index === activeIndex ? -1 : index);
  };
  return(
    <>
      <ul>
        {MenuArray.map((item, index) =>
          <li
            key={index}
            className={`menu ${
              index === activeIndex ? "active" : ""
            }`}
            onClick={() => handleToggleMenu(index)}
          >
            {item.title}
          </li>
        )}
      </ul>
    </>
  )
}

export default Test;

하나의 useState를 사용하여 4개의 메뉴에 각각 onClick 이벤트를 적용시켜 클릭한 메뉴에만 active 클래스를 추가/제거한다.