All files / components/Form/InputCheck InputCheck.tsx

100% Statements 57/57
100% Branches 5/5
100% Functions 1/1
100% Lines 57/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 581x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 8x 8x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x  
import { forwardRef, useEffect, useRef, useState } from 'react';
 
import { c } from '../../../helpers';
import { IconCheck } from '../../Icons';
import { InputCheckPosition } from './InputCheckConstants';
import type { InputCheckProps } from './InputCheckProps';
 
import styles from './InputCheck.module.css';
 
const InputCheck = forwardRef<HTMLInputElement, InputCheckProps>(
  (
    {
      checked,
      className,
      disabled,
      label,
      onChange,
      position = InputCheckPosition.LEFT,
    }: InputCheckProps,
    ref: React.ForwardedRef<HTMLInputElement>
  ) => {
    const inputRef = useRef<HTMLInputElement>(null);
    const [isChecked, setIsChecked] = useState<boolean>(checked ?? false);
 
    if (ref == null) {
      ref = inputRef;
    }
 
    useEffect(() => {
      if (typeof ref === 'object' && ref?.current != null) {
        ref.current.checked = isChecked;
      }
    }, [isChecked, ref]);
 
    const handleOnChange = (
      event: React.ChangeEvent<HTMLInputElement>
    ): void => {
      onChange && onChange(event.target.checked);
      setIsChecked(event.target.checked);
    };
 
    return (
      <label className={c(styles.checkbox, styles[position], className)}>
        <input
          ref={ref}
          type="checkbox"
          disabled={disabled}
          onChange={handleOnChange}
        />
        <IconCheck className={c(styles.icon_check)} />
        <span>{label}</span>
      </label>
    );
  }
);
 
export default InputCheck;