checkbox.tsx 837 B

123456789101112131415161718192021222324252627282930313233
  1. import {useEffect, useRef} from 'react';
  2. type CheckboxProps = React.InputHTMLAttributes<HTMLInputElement>;
  3. interface Props extends Omit<CheckboxProps, 'checked'> {
  4. /**
  5. * Is the checkbox active? Supports 'indeterminate'
  6. */
  7. checked?: CheckboxProps['checked'] | 'indeterminate';
  8. }
  9. const Checkbox = ({checked = false, ...props}: Props) => {
  10. const checkboxRef = useRef<HTMLInputElement>(null);
  11. // Support setting the indeterminate value, which is only possible through
  12. // setting this attribute
  13. useEffect(() => {
  14. if (checkboxRef.current) {
  15. checkboxRef.current.indeterminate = checked === 'indeterminate';
  16. }
  17. }, [checked]);
  18. return (
  19. <input
  20. ref={checkboxRef}
  21. checked={checked !== 'indeterminate' && checked}
  22. type="checkbox"
  23. {...props}
  24. />
  25. );
  26. };
  27. export default Checkbox;