useCheckBox 커스텀 훅

혜진 조·2022년 10월 17일
0

리액트

목록 보기
16/31
post-custom-banner
import { ChangeEvent, useState } from "react";

type useCheckBoxProps = [(e: ChangeEvent<HTMLInputElement>) => void, string[]];

const useCheckBox = (): useCheckBoxProps => {
  
  const [checkedInputs, setCheckedInputs] = useState<string[]>([]);
  
  const changeHandler = (e: ChangeEvent<HTMLInputElement>) => {    
    const checkboxes = document.querySelectorAll("input[type=checkbox]");

    if (!checkedInputs.includes(e.target.name)) {
      if (
        e.target.name === "전체선택" ||
        checkedInputs.length === checkboxes.length - 2
      ) {
        let arr: string[] = [];
        checkboxes.forEach((checkbox: any) => arr.push(checkbox.name));
        setCheckedInputs(arr);
      } else {
        setCheckedInputs([...checkedInputs, e.target.name]);
      }
    } else {
      if (e.target.name === "전체선택") {
        setCheckedInputs([]);
      } else {
        setCheckedInputs(
          checkedInputs.filter(
            (el) => el !== e.target.name && el !== "전체선택"
          )
        );
      }
    }
  };
  return [changeHandler, checkedInputs];
};

export default useCheckBox;

  const [changeHandler, checkedInputs] = useCheckBox();

//...

		<CheckBox
          label="전체 선택"
          name={"전체선택"}
          checked={checkedInputs.includes("전체선택")}
          onChange={(e: ChangeEvent<HTMLInputElement>) => changeHandler(e)}
        />
		{data.map(({miniShop},idx)=>(
          <CheckBox
            name={miniShop}
            checked={checkedInputs.includes(miniShop)}
            onChange={(e: ChangeEvent<HTMLInputElement>) => changeHandler(e)}
          />
		))}
		  
profile
나를 믿고 한 걸음 한 걸음 내딛기! 🍏
post-custom-banner

0개의 댓글