mercredi 2 septembre 2020

How to handle multiple checkboxes using React Hook

I need to control all checkboxes using hooks in React

Code for parent

const Filter = () => {

  const [isChecked, setIsChecked] = useState({
    all: false,
    without: false,
    one: false,
    two: false,
    three: false,
  })

  const handleChange = ({ target : { name, checked } }) => {
    setIsChecked({ 
      ...isChecked, 
      [name]: checked 
    })
  }

  const checkboxes = [
    {
      key: "all",
      name: "all",
      htmlFor: "all",
      label: "Все"
    },
    {
      key: "without",
      name: "without",
      htmlFor: "without",
      label: "Без пересадок"
    },
    {
      key: "one",
      name: "one",
      htmlFor: "one",
      label: "1 пересадка"
    },
    {
      key: "two",
      name: "two",
      htmlFor: "two",
      label: "2 пересадки"
    },
    {
      key: "three",
      name: "three",
      htmlFor: "three",
      label: "3 пересадки"
    },
  ];
  return (
    <div className="content__filter">
      <div className="content__filter__name">
        Количество пересадок
      </div>
      <div className="content__filter__list">
        <ul>
          {checkboxes.map(item => (
            <ListItem 
              key={item.key}
              name={item.name} 
              htmlFor={item.htmlFor} 
              label={item.label}
              checked={isChecked[item.name]}
              onChange={handleChange}
            />
          ))}
        </ul>
      </div>
    </div>
  );
};

export default Filter;

Code for children

const ListItem = ({ type = "checkbox", name, htmlFor, label, onChange, checked }) => {
  console.log(checked)
  return (
    <li>
      <input type={type} name={name} checked={checked} onChange={onChange}/>
      <label htmlFor={htmlFor}>{label}</label>
    </li>
  )
};

export default ListItem;

Checkboxes don't react at all. I mean if I click, nothing happens. I get false property all the time in the children and it can't be switched. Also it doesn't work if I set isChecked as an empty object (like in this example https://codesandbox.io/s/react-hooks-usestate-xzvq5?file=/src/index.js:380-382) What am I doing wrong? Any help appreciated




Aucun commentaire:

Enregistrer un commentaire