Home > Blockchain >  Checkbox for select all in react js
Checkbox for select all in react js

Time:07-07

I wanted to create a select-all checkbox, each product row has a checkbox, once the checkbox is clicked it will take its product id, variations, and count to calculate and display the total price of the product selected. I wanted to do like when clicking on select all, all the other checks need to tick and display the total of all product prices, I did the code for each row checkbox and it work but I am not sure how to do for select all checkbox, need help on it, below are code, and https://codesandbox.io/s/select-all-checkbox-uzmllg this is codesand box.

import "./styles.css";
import React, { useEffect, useState } from "react";
export default function App() {
  const [isCheckAll, setIsCheckAll] = useState(false);
  const [checkedItems, setCheckedItems] = useState(
    JSON.parse(localStorage.getItem("checkedItems") || "[]")
  );
  useEffect(() => {
    localStorage.setItem("checkedItems", JSON.stringify(checkedItems));
  }, [checkedItems]);
  const addChecked = (itemId, variationId, qty) => {
    setCheckedItems([
      ...checkedItems,
      { ProductID: itemId, VariationID: variationId, Count: qty }
    ]);
  };

  const removeChecked = (itemId, variationId) => {
    const toBeRemove = checkedItems.find(
      (item) => item.ProductID === itemId && item.VariationID === variationId
    );

    if (toBeRemove) {
      checkedItems.splice(checkedItems.indexOf(toBeRemove), 1);
      setCheckedItems([...checkedItems]);
    }
  };

  const getCheckedStatus = (itemId, variationId) => {
    const found = checkedItems.find(
      (item) => item.ProductID === itemId && item.VariationID === variationId
    );

    return found !== null;
  };

  const handleSelectAll = (e) => {
    if (isCheckAll) {
      //
    }
  };
  return (
    <div className="App">
      {cartData.Result.map((shop) =>
          shop.ShopCartList.map((cart) => (
            <div key={cart.ShopID} md="12" lg="12">
              
                {cart.productCartList.map((items) => {
                  return (
                    <div key={items.VariationID} md="12" lg="12">
                      
                              <div id="additem" className="pt-5">
                                {items.Stock === 0 ? (
                                  <h6 className="bg-light text-danger font-weight-bold ">
                                    SOLD OUT
                                  </h6>
                                ) : (
                                  <input
                                    type="checkbox"
                                    value={getCheckedStatus(
                                      items.ProductID,
                                      items.VariationID
                                    )}
                                    onChange={(e) => {
                                      if (e.target.checked) {
                                        addChecked(
                                          items.ProductID,
                                          items.VariationID,
                                          items.Count
                                        );
                                      } else {
                                        removeChecked(
                                          items.ProductID,
                                          items.VariationID,
                                          items.Count
                                        );
                                      }
                                    }}
                                  />
                                )}
                              </div>
                      </div>
                  );
                })}
              </div>
            
          ))
        )}
      <div>
        <input
          type="checkbox"
          name="selectAll"
          id="selectAll"
          handleClick={handleSelectAll}
          isChecked={isCheckAll}
        />
        Select All
      </div>
    </div>
  );
}

CodePudding user response:

In handleSelectAll you need to set checkedItems is all your array items. You dont need isCheckAll state, you can see check all status by verify length of your checkedItems

const flattenCartData = (cartData) => {
  const arr = [];
  cartData.Result.forEach((shop) => {
    shop.ShopCartList.forEach((cart) => {
      cart.productCartList.forEach((items) => {
        arr.push(items);
      });
    });
  });
  return arr;
};

export default function App() {
  const [checkedItems, setCheckedItems] = useState(
    JSON.parse(localStorage.getItem("checkedItems") || "[]")
  );
  const ITEMS = flattenCartData(cartData);
  const isCheckAll = checkedItems.length === ITEMS.length;
  useEffect(() => {
    localStorage.setItem("checkedItems", JSON.stringify(checkedItems));
  }, [checkedItems]);
  const addChecked = (itemId, variationId, qty) => {
    setCheckedItems([
      ...checkedItems,
      { ProductID: itemId, VariationID: variationId, Count: qty }
    ]);
  };

  const removeChecked = (itemId, variationId) => {
    const toBeRemove = checkedItems.find(
      (item) => item.ProductID === itemId && item.VariationID === variationId
    );

    if (toBeRemove) {
      checkedItems.splice(checkedItems.indexOf(toBeRemove), 1);
      setCheckedItems([...checkedItems]);
    }
  };

  const getCheckedStatus = (itemId, variationId) => {
    const found = checkedItems.find(
      (item) => item.ProductID === itemId && item.VariationID === variationId
    );

    return found !== undefined;
  };

  const handleSelectAll = (e) => {
    if (isCheckAll) {
      setCheckedItems([]);
    } else setCheckedItems([...ITEMS]);
  };

  return (
    <div className="App">
      {cartData.Result.map((shop) =>
        shop.ShopCartList.map((cart) => (
          <div key={cart.ShopID} md="12" lg="12">
            {cart.productCartList.map((items) => {
              return (
                <div key={items.VariationID} md="12" lg="12">
                  <div id="additem" className="pt-5">
                    {items.Stock === 0 ? (
                      <h6 className="bg-light text-danger font-weight-bold ">
                        SOLD OUT
                      </h6>
                    ) : (
                      <div>
                        <input
                          type="checkbox"
                          checked={getCheckedStatus(
                            items.ProductID,
                            items.VariationID
                          )}
                          onChange={(e) => {
                            if (e.target.checked) {
                              addChecked(
                                items.ProductID,
                                items.VariationID,
                                items.Count
                              );
                            } else {
                              removeChecked(
                                items.ProductID,
                                items.VariationID,
                                items.Count
                              );
                            }
                          }}
                        />
                        <span>{items.ProductName}</span>
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        ))
      )}
      <div>
        <input
          type="checkbox"
          name="selectAll"
          id="selectAll"
          onChange={handleSelectAll}
          checked={isCheckAll}
        />
        Select All
      </div>
    </div>
  );
}

I have created a codesandbox. You can check, hope it help!

  • Related