All files / inputRadio index.tsx

0% Statements 0/12
0% Branches 0/14
0% Functions 0/4
0% Lines 0/11

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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80                                                                                                                                                               
import React, { useState, useCallback } from 'react';
import cx from 'classnames';
 
import { FieldInputProps, IOption } from '../types';
 
/**
 * Input Radio component.
 */
interface IInputRadio {
  /** Passed down classname. */
  className?: string;
  /** Optional id indicator */
  id?: string;
  /** Input props from react-final-form */
  input: FieldInputProps<HTMLElement>;
  /** If background has a solid color */
  isReverse?: boolean;
  /** Is small */
  isSmall?: boolean;
  /** Mandatory option list */
  options: IOption[];
  /** Optional title */
  title?: string;
}
 
export const InputRadio: React.FC<IInputRadio> = ({
  id,
  input: { onChange, value },
  isSmall = false,
  isReverse = false,
  options,
  title,
}) => {
  const combinedLabelClass =
    !!title &&
    cx({
      'panda-input-title--large': !isSmall,
      'panda-input-title--small': isSmall,
      'panda-input-title--white': isReverse,
    });
  const combinedRadioContainerClass = cx({
    'panda-input-radio-container': true,
    'panda-typography--P2': isSmall,
    'panda-typography--P1': !isSmall,
    'panda-input-radio-container--small': isSmall,
    'panda-input-radio-container--large': !isSmall,
    'panda-input-radio-container--reverse': isReverse,
  });
 
  const [activeValue, setActiveValue] = useState(value || options[0].value);
  const onValueClick = useCallback(
    (option: IOption) => {
      if (option.value === activeValue) return;
      setActiveValue(option.value);
      onChange && onChange(option.value);
    },
    [activeValue, onChange],
  );
 
  return (
    <div className="panda-input-container" id={id}>
      {!!title && <label className={combinedLabelClass || ''}>{title}</label>}
      <div className={combinedRadioContainerClass}>
        {options.map((option: IOption, index: number) => (
          <button
            tabIndex={0}
            key={index}
            className={cx('panda-input-radio text-ellipsis', {
              'panda-input-radio--active': activeValue === option.value,
            })}
            onClick={() => onValueClick(option)}
          >
            {option.name}
          </button>
        ))}
      </div>
    </div>
  );
};