Last active
May 22, 2024 03:30
-
-
Save Ah-ae/f089382443c13c27bbbe0df9492e1743 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useEffect, useRef } from 'react'; | |
| type Props = { | |
| id?: number; | |
| label?: React.ReactNode; | |
| checked: boolean; | |
| handleCheckbox: (checked: boolean, id: number) => void; | |
| indeterminate?: boolean; | |
| }; | |
| export default function CheckBox({ id, label, checked, handleCheckbox, indeterminate }: Props) { | |
| const checkboxRef = useRef<HTMLInputElement>(null); | |
| useEffect(() => { | |
| if (checkboxRef.current) { | |
| checkboxRef.current.indeterminate = !!indeterminate; | |
| } | |
| }, [indeterminate]); | |
| return ( | |
| <label className="flex items-center"> | |
| <input | |
| ref={checkboxRef} | |
| type="checkbox" | |
| id={id ? String(id) : undefined} | |
| checked={checked} | |
| onChange={(event) => { | |
| handleCheckbox(event.target.checked, id ?? -1); | |
| }} | |
| className="hidden" | |
| /> | |
| <span | |
| className={`w-4 h-4 flex items-center justify-center border rounded-sm cursor-pointer ${ | |
| checked ? 'bg-blue-500 border-blue-500' : 'bg-white border-gray-300' | |
| } ${indeterminate ? 'bg-blue-500 border-blue-500' : ''}`} | |
| onMouseDown={(event) => event.preventDefault()} // Prevent text selection | |
| > | |
| {indeterminate ? ( | |
| <span className="text-white font-bold">-</span> | |
| ) : ( | |
| checked && ( | |
| <svg | |
| className="size-2 text-white" | |
| fill="none" | |
| stroke="currentColor" | |
| viewBox="0 0 24 24" | |
| xmlns="http://www.w3.org/2000/svg" | |
| > | |
| <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path> | |
| </svg> | |
| ) | |
| )} | |
| </span> | |
| {label && <span className="ml-2">{label}</span>} | |
| </label> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment