Home > database >  React checkbox: Select one and disable others
React checkbox: Select one and disable others

Time:08-28

Initially every items should active but When someone click on any items the others will disable/opacity(0.5). How to do that, I have tried a lot but can't find any solution.

  const handleCheckbox = (e) => {
    setActive(!active)
    let selected = [...selectedHobby]
    if (e.target.checked) {
      selected = [...selectedHobby, e.target.value]
    } else {
      selected.splice(selectedHobby.indexOf(e.target.value), 1)
    }
    setSelectedHobby(selected)
    router.push({
      pathname: '',
      query: { ...router.query, 'search': selected }
    })
  }

  return (<>
    <div className={`${active ? 'deactive' : 'active'}`}>
      <input
        type="checkbox"
        name={props.name}
        value={props.value}
        onChange={(e) => handleCheckbox(e)}
      /> {props.label}
    </div>
  </>
  )
}
.deactive {
  opacity: 0.50;
}

Sandbox: https://codesandbox.io/s/aged-butterfly-ch7u13?file=/src/App.js

CodePudding user response:

Here is solution.

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

let fruits = ["orange", "lemon", "apple", "watermelon"];

const Check = (props) => {
  const handleCheckbox = (name) => {
    const findIndex = props.selectedHobby.findIndex((v) => v === name);
    if (findIndex === -1) {
      return props.setSelectedHobby((array) => [...array, name]);
    }
    return props.setSelectedHobby((array) => array.filter((v) => v !== name));
  };
  return (
    <>
      <div
        className={`${
          props.selectedHobby.length === 0
            ? "active"
            : props.selectedHobby.includes(props.name)
            ? "active"
            : "deactive"
        }`}
      >
        <input
          type="checkbox"
          name={props.name}
          value={props.value}
          onChange={(e) => handleCheckbox(props.name)}
        />{" "}
        {props.label}
      </div>
    </>
  );
};

const HobbyCheck = () => {
  const [selectedHobby, setSelectedHobby] = useState([]);

  return (
    <>
      {fruits.map((fruit, key) => (
        <Check
          selectedHobby={selectedHobby}
          setSelectedHobby={setSelectedHobby}
          key={key}
          label={fruit}
          name={fruit}
        />
      ))}
    </>
  );
};

export default HobbyCheck;

Screenshot of output

CodePudding user response:

You might want to store the state of the items in HobbyCheck component and not in the Check component. And set up two way binding.

  • Related