All files / src/core/components/carbon controlled-radio-button-group.component.tsx

50% Statements 5/10
16.66% Branches 1/6
60% Functions 3/5
55.55% Lines 5/9

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                                1x 2x   2x         2x                                   4x                            
import React from 'react';
import { type RadioButtonGroupProps } from '@carbon/react/lib/components/RadioButtonGroup/RadioButtonGroup';
import { type Control, Controller, type FieldValues } from 'react-hook-form';
import { RadioButtonGroup, RadioButton } from '@carbon/react';
import { type RadioOption } from '../../../stock-items/add-stock-item/stock-item-details/stock-item-details.resource';
 
interface ControlledRadioButtonGroupProps<T>
  extends Omit<RadioButtonGroupProps, 'onChange' | 'id' | 'ref' | 'value' | 'defaultSelected'> {
  controllerName: string;
  name: string;
  control: Control<FieldValues, T>;
  options: RadioOption[];
  id?: string;
  onChange?: (selectedValue: string, name: string, event: React.ChangeEvent<HTMLInputElement>) => void;
}
 
const ControlledRadioButtonGroup = <T,>(props: ControlledRadioButtonGroupProps<T>) => {
  const { controllerName, name, control, options, onChange: onChangeProp, id: propsId, ...radioGroupProps } = props;
 
  return (
    <Controller
      name={controllerName}
      control={control}
      render={({ field: { onChange, value, ref } }) => (
        <RadioButtonGroup
          {...radioGroupProps}
          name={name}
          onChange={(selectedValue: string, name: string, event: React.ChangeEvent<HTMLInputElement>) => {
            const matchedOption = options.find((option) => String(option.value) === selectedValue);
            onChange(matchedOption ? matchedOption.value : selectedValue);
 
            // Fire prop change
            if (onChangeProp) {
              onChangeProp(selectedValue, name, event);
            }
          }}
          id={name}
          ref={ref}
          defaultSelected={propsId}
          valueSelected={value != null ? String(value) : value}
        >
          {options.map((option, index) => (
            <RadioButton
              key={`${index}-${name}-${option.value}`}
              id={`${name}-${option.value}`}
              labelText={option.label}
              value={String(option.value)}
            />
          ))}
        </RadioButtonGroup>
      )}
    />
  );
};
 
export default ControlledRadioButtonGroup;