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)}
/>
))}