UNPKG

@atlaskit/radio

Version:

A radio input allows users to select only one option from a number of choices. Radio is generally displayed in a radio group.

60 lines (59 loc) 1.94 kB
import _extends from "@babel/runtime/helpers/extends"; import React, { useCallback, useState } from 'react'; import noop from '@atlaskit/ds-lib/noop'; import { useId } from '@atlaskit/ds-lib/use-id'; import Radio from './radio'; const noOptions = []; export default function RadioGroup(props) { const { onChange, options = noOptions, value: propValue, defaultValue, id, isDisabled, isRequired, isInvalid, onInvalid = noop, name, analyticsContext, ['aria-labelledby']: ariaLabelledBy, testId } = props; const uid = useId(); const [selectedValue, setSelectedValue] = useState(propValue !== undefined ? propValue : defaultValue); const onRadioChange = useCallback((e, analyticsEvent) => { setSelectedValue(e.currentTarget.value); if (onChange) { onChange(e, analyticsEvent); } }, [onChange]); // If propValue is provided than act as a controlled component // If not then act as an uncontrolled component using the value from state const value = typeof propValue !== 'undefined' ? propValue : selectedValue; return /*#__PURE__*/React.createElement("div", { role: "radiogroup", "aria-labelledby": ariaLabelledBy, "data-testid": testId, "aria-describedby": isInvalid ? `${id || uid}-error` : undefined, id: id || uid }, options.map(({ ...optionProps }, index) => { if (typeof isDisabled !== 'undefined') { optionProps.isDisabled = isDisabled; } const isChecked = value !== null && optionProps.value === value; return /*#__PURE__*/React.createElement(Radio, _extends({}, optionProps, { name: name || optionProps.name, key: index, onChange: onRadioChange, onInvalid: onInvalid, isInvalid: isChecked && isInvalid, isChecked: isChecked, testId: optionProps.testId || testId, isRequired: isRequired, analyticsContext: analyticsContext })); })); }