Home > database >  React map only checks the last checkbox
React map only checks the last checkbox

Time:11-21

I have a 2 sets of unique checkboxes and each one has its own fields, and some of them are checked, so I would like to check the selected ones by default on page load, but for some reason it only selects the last checkbox and ignores the first list

You can check it out here at codesandbox

import React, { Component, useState, useRef, useEffect } from "react";
import ReactDOM from "react-dom";
import { Checkbox, Pane, Label } from "evergreen-ui";

function ControlledCheckboxExample() {
  const [checked, setChecked] = React.useState(true);
  const [fieldchecked, setIsFieldChecked] = React.useState(false);
  const [editContactFields, setContactFields] = React.useState([]);
  useEffect(() => {
    loaddata();
  }, []);
  const loaddata = () => {
    let data = [
      {
        id: 1,
        label: "First Checkbox",
        type: "checkbox",
        selectedvalue: [
          {
            value: "one"
          },
          {
            value: "two"
          }
        ],
        hasvalue: true,
        tag: "UNIQUEONE",
        options: [
          {
            value: "one",
            text: "one"
          },
          {
            value: "two",
            text: "two"
          },
          {
            value: "three",
            text: "three"
          },
          {
            value: "four",
            text: "four"
          }
        ],
        visible: true
      },
      {
        id: 2,
        label: "Second Checkbox",
        type: "checkbox",
        selectedvalue: [
          {
            value: "five"
          }
        ],
        hasvalue: true,
        tag: "UNIQUETWO",
        options: [
          {
            value: "five",
            text: "five"
          }
        ],
        visible: true
      }
    ];
    setContactFields(data);
    data.map((field, index) => {
      if (field.type === "checkbox" && field.hasvalue == true) {
        setIsFieldChecked(false);
        let value = field.selectedvalue;
        let tag = field.tag;
        value.map((realvalue) => {
          let fieldvalud = realvalue.value;
          setIsFieldChecked((fieldchecked) => ({
            ...fieldchecked,
            [fieldvalud   tag]: !fieldchecked[fieldvalud   tag]
          }));
        });
      }
    });
  };

  const handlefieldchecked = (a, f) => {
    const fieldvalud = a;
    const tag = f;

    setIsFieldChecked((fieldchecked) => ({
      ...fieldchecked,
      [fieldvalud   tag]: !fieldchecked[fieldvalud   tag]
    }));
  };

  return (
    <Pane>
      {editContactFields.map((field) => (
        <Pane>
          <Label>
            {field.label} {field.required == true && "*"}
          </Label>
          {field.options.map((checkboxfield) => (
            <Checkbox
              name={field.tag   "[]"}
              id={field.tag}
              type={field.type}
              value={checkboxfield.value}
              label={checkboxfield.text}
              checked={fieldchecked[checkboxfield.value   field.tag]}
              required={field.required}
              onChange={(e) =>
                handlefieldchecked(checkboxfield.value, field.tag)
              }
            />
          ))}
        </Pane>
      ))}
    </Pane>
  );
}

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

When I remove the second set of checkboxes, it works like it should be, but as soon as I add it, it ignores the first ones.

Is there a way to make it work properly?

CodePudding user response:

When you're mapping over the data you reset fieldchecked with setIsFieldChecked(false); which will result in only having the values of the last iteration of the map.

data.map((field, index) => {
  if (field.type === "checkbox" && field.hasvalue == true) {
    // setIsFieldChecked(false); => remove this
    let value = field.selectedvalue;
    let tag = field.tag;
    value.map((realvalue) => {
      let fieldvalud = realvalue.value;
      setIsFieldChecked((fieldchecked) => ({
        ...fieldchecked,
        [fieldvalud   tag]: !fieldchecked[fieldvalud   tag],
      }));
    });
  }
});
  • Related