mardi 30 juin 2020

React Multiple Checkboxes are not visible as selected after change

I have a list of checkboxes. Checkbox is not visible as selected even after the value has been changed.

Below is my code: -

import React, { useState } from "react";
import { render } from "react-dom";

const CheckboxComponent = () => {
  const [checkedList, setCheckedList] = useState([
    { id: 1, label: "First", isCheck: false },
    { id: 2, label: "Second", isCheck: true }
  ]);

  const handleCheck = (e, index) => {
    checkedList[index]["isCheck"] = e.target.checked;
    setCheckedList(checkedList);
    console.log(checkedList);
  };

  return (
    <div className="container">
      {checkedList.map((c, index) => (
        <div>
          <input
            id={c.id}
            type="checkbox"
            checked={c.isCheck}
            onChange={e => handleCheck(e, index)}
          />
          <label htmlFor={c.id}>{c.label}</label>
        </div>
      ))}
    </div>
  );
};

render(<CheckboxComponent />, document.getElementById("root"));

I was working fine for a simple checkbox outside the loop. I am not sure where is the problem.

Here is the link - https://codesandbox.io/s/react-multiple-checkboxes-sczhy?file=/src/index.js:0-848




Aucun commentaire:

Enregistrer un commentaire