@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.
64 lines (63 loc) • 2.58 kB
JavaScript
import _objectDestructuringEmpty from "@babel/runtime/helpers/objectDestructuringEmpty";
import _extends from "@babel/runtime/helpers/extends";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
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';
var noOptions = [];
export default function RadioGroup(props) {
var onChange = props.onChange,
_props$options = props.options,
options = _props$options === void 0 ? noOptions : _props$options,
propValue = props.value,
defaultValue = props.defaultValue,
id = props.id,
isDisabled = props.isDisabled,
isRequired = props.isRequired,
isInvalid = props.isInvalid,
_props$onInvalid = props.onInvalid,
onInvalid = _props$onInvalid === void 0 ? noop : _props$onInvalid,
name = props.name,
analyticsContext = props.analyticsContext,
ariaLabelledBy = props['aria-labelledby'],
testId = props.testId;
var uid = useId();
var _useState = useState(propValue !== undefined ? propValue : defaultValue),
_useState2 = _slicedToArray(_useState, 2),
selectedValue = _useState2[0],
setSelectedValue = _useState2[1];
var onRadioChange = useCallback(function (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
var value = typeof propValue !== 'undefined' ? propValue : selectedValue;
return /*#__PURE__*/React.createElement("div", {
role: "radiogroup",
"aria-labelledby": ariaLabelledBy,
"data-testid": testId,
"aria-describedby": isInvalid ? "".concat(id || uid, "-error") : undefined,
id: id || uid
}, options.map(function (_ref, index) {
var optionProps = _extends({}, (_objectDestructuringEmpty(_ref), _ref));
if (typeof isDisabled !== 'undefined') {
optionProps.isDisabled = isDisabled;
}
var 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
}));
}));
}