본문 바로가기

NEW(스크립트용)

react useState 로 토글버튼 만들기

import React, { useState } from "react";
import "./UseState.css";
import "../../App.css";
const EachUseState = () => {
  const btnarr = [
    { id: 1, name: "apple" },
    { id: 2, name: "bannan" },
    { id: 3, name: "melon" }
  ];
  const [fruits, setFruits] = useState(btnarr);
  const [select, setSelect] = useState([]);

  return (
    <div
      className="flex"
      style={{
        columnGap: "10px"
      }}
    >
      {fruits.map((fruit) => (
        <div
          className={select.includes(fruit) ? "gray_boxcss" : "boxcss"}
          index={fruit.id}
          onClick={() => {
            console.log(fruit);
            !select.includes(fruit)
              ? setSelect((select) => [...select, fruit])
              : setSelect(select.filter((filtered) => filtered !== fruit));
          }}
        >
          {fruit.name}
        </div>
      ))}
    </div>
  );
};

export default EachUseState;
.boxcss {
  width: 40px;
  height: 40px;
  background-color: rgb(182, 121, 121);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
.gray_boxcss {
  width: 40px;
  height: 40px;
  background-color: rgb(159, 159, 159);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}