UNPKG

glide-design-system

Version:

Glide design system is an open-source React component library. It offers numerous benefits that make them essential tools for design and development teams.

123 lines (111 loc) 3.21 kB
import React, { useRef, useEffect, useState } from "react"; import Classes from "./CheckBoxGroup.module.css"; const CheckboxGroup = ({ options, label, onChange, style, className, required, labelStyle, value, defaultValue, name, }) => { const checkBoxRefs = useRef([]); const [checkedItems, setCheckedItems] = useState([]); const [checkBox, setCheckBox] = useState([options]); // console.log(value) useEffect(() => { if (value) { // console.log(value, "checl"); setCheckedItems(value); } else if (defaultValue) { setCheckedItems(defaultValue); } else { setCheckedItems([]); } checkBoxRefs.current = Array(options?.length) .fill() .map((_, i) => checkBoxRefs?.current[i] || React.createRef()); }, [options?.length, value, defaultValue]); const selectField = (index) => { checkBoxRefs?.current[index].current?.click(); }; const onCheckboxChange = (event, option) => { const isChecked = event?.target?.checked; setCheckedItems((prevItems) => { let updatedItems; if (isChecked) { updatedItems = [...prevItems, option]; } else { updatedItems = prevItems.filter((item) => item !== option); } onChange(updatedItems); return updatedItems; }); }; const combinedStyle = { ...style, }; const headerStyle = { ...labelStyle, }; useEffect(() => { setCheckBox(options); }, [options]); // console.log(checkedItems,"check") return ( <div> <p style={headerStyle} className={Classes.headers}> {label} {required && <span className={Classes.required}>*</span>} </p> <div style={combinedStyle} className={`${className ? className : ""} ${Classes.checkBox}`}> {checkBox?.map((option, index) => ( <div className={`${Classes.container}`} key={option?.value}> <input ref={checkBoxRefs?.current[index]} type="checkbox" id={option?.id} name={name} value={option?.value} checked={checkedItems?.includes(option?.value)} onChange={(e) => { onCheckboxChange(e, option?.value); }} /> <label onClick={() => { selectField(index); }} htmlFor={option?.value} className={`${Classes.checkmark}`} style={{ cursor: "pointer", marginTop: "2px" }}></label> <label onClick={() => { selectField(index); }} htmlFor={option?.value} style={{ fontFamily: combinedStyle?.fontFamily ? combinedStyle?.fontFamily : "Roboto, sans-serif", cursor: "pointer", marginLeft: "6px", fontSize: combinedStyle?.fontSize ? combinedStyle?.fontSize : "14px", }}> {option?.label} </label> <br /> </div> ))} </div> </div> ); }; export default CheckboxGroup;