jeudi 29 octobre 2020

How to make the checkbox checked default?

I am making a react app where I need to populate dynamic checkboxes from the data.

  const sectors = [
    {
      SectorID: 5,
      Name: "Wood Truss/Panel/Building Components"
    },
    {
      SectorID: 33,
      Name: "LBM Retail/Pro Contractor"
    },
    {
      SectorID: 24,
      Name: "Light Gauge Steel Truss/Panel"
    }
  ];

Then I do have a list of selected checkboxes here,

  const selectedSectors = [
    {
      SectorID: 5
    },
    {
      SectorID: 24
    }
  ];

So here using SectorID, we can find a match.

Expected result: Need to make the selected sector to be checked on load.

Solution I tried:

  const [checkedItems, setCheckedItems] = useState({});

  React.useEffect(() => {
    const newData = sectors.map((sector) => {
      return selectedSectors.map((selected) => {
        if (selected.SectorId === sector.SectorId) {
          setCheckedItems((prev) => {
            const checkedItems = {
              ...prev.checkedItems,
              [sector.Name]: true
            };
            return { ...prev, checkedItems };
          });
        }
      });
    });
  }, []);

The above one doesn't make the selected sectors checked and I think I am doing something wrong here.

Populating checkboxes like:

      {sectors &&
        sectors.map((sector, index) => (
          <React.Fragment key={index}>
            <label className="block mr-4">
              <input
                className="mx-2 leading-tight"
                name={sector.Name}
                checked={checkedItems[sector.Name]}
                onChange={(e) => handleInputChange(e, sector)}
                type="checkbox"
              />
              <span className="text-sm">{sector.Name}</span>
            </label>
          </React.Fragment>
        ))}

Codesandbox:

Edit React Functional Component (forked)

Requirement: Please help me to make the checkboxes get checked by default on comparing with selectedSectors..




Aucun commentaire:

Enregistrer un commentaire