각각의 버튼 클릭시 active클래스부여 (map으로렌더링시)

5o_hyun·2022년 11월 11일
0


각각의 버튼을 클릭시 active클래스를 주었다.
초기값은 0으로 맞춰 첫번째버튼이 active되게 만들었고,
클릭한 timeActiveIndex와 === timeGroup의 index값일치하면 active클래스를 주게 만들었다.

function Home() {
 const timeGroup = [
    { id: 1, time: '10:00' },
    { id: 2, time: '11:00' },
    { id: 3, time: '12:00' },
    { id: 4, time: '14:00' },
    { id: 5, time: '15:00' },
    { id: 6, time: '16:00' },
    { id: 7, time: '17:00' },
  ];

 
  const [timeActiveIndex, setTimeActiveIndex] = useState(0);
  const timeToggleActive = (index: number) => {
    setTimeActiveIndex(index);
  };

  return (
    <div className="container">
    	{timeGroup.map((item, index) => (
    	<div
    		className={timeActiveIndex === index ? 'active' : ''}
			onClick={() => timeToggleActive(index)}
  		>
    	{item.time}
		</div>
		))}
    </div>
  );
}

export default Home;
profile
학생 점심 좀 차려

0개의 댓글