score:2

Accepted answer

Here is something I made very quickly just to show a working example (can be much better and shorter but I thought this will help make it more understandable). If you need any extra help, will be happy to update my answer ;)

import { useState } from "react";
import "./styles.css";

const initialCheckBoxesState = [
  { name: "one", checked: false },
  { name: "two", checked: false },
  { name: "three", checked: false },
  { name: "four", checked: false },
  { name: "five", checked: false }
];

export default function App() {
  const [checkBoxes, setCheckedBoxes] = useState(initialCheckBoxesState);
  const [error, setError] = useState("");

  const handleCheckOnClick = (event) => {
    setError("");
    let checkBoxIndex = checkBoxes.findIndex(
      (box) => box.name === event.target.name
    );
    let copyOfCheckBoxes = [...checkBoxes];
    let isChecked = copyOfCheckBoxes[checkBoxIndex].checked;
    let amountOfCheckedBoxes = checkBoxes.filter((box) => box.checked);

    if (!isChecked && amountOfCheckedBoxes.length > 2) {
      setError("Max of 3 checked checkboxes");
      return;
    }

    if (isChecked) {
      copyOfCheckBoxes[checkBoxIndex] = {
        ...copyOfCheckBoxes[checkBoxIndex],
        checked: false
      };
    } else {
      copyOfCheckBoxes[checkBoxIndex] = {
        ...copyOfCheckBoxes[checkBoxIndex],
        checked: true
      };
    }

    setCheckedBoxes(copyOfCheckBoxes);
  };

  return (
    <div className="App">
      {checkBoxes.map((box, index) => {
        return (
          <input
            key={index}
            type="checkbox"
            name={box.name}
            onChange={handleCheckOnClick}
            checked={box.checked}
          />
        );
      })}
      <span>{error}</span>
    </div>
  );
}

Related Query

More Query from same tag