@carbon/react
Version:
React components for the Carbon Design System
138 lines (136 loc) • 5.98 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { usePrefix } from "../../internal/usePrefix.js";
import { useId } from "../../internal/useId.js";
import { deprecate } from "../../prop-types/deprecate.js";
import { isComponentElement } from "../../internal/utils.js";
import { AILabel } from "../AILabel/index.js";
import { mergeRefs } from "../../tools/mergeRefs.js";
import { Legend } from "../Text/createTextComponent.js";
import classNames from "classnames";
import React, { cloneElement, createContext, useEffect, useRef, useState } from "react";
import PropTypes from "prop-types";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { WarningAltFilled, WarningFilled } from "@carbon/icons-react";
createContext(null);
const RadioButtonGroup = React.forwardRef((props, ref) => {
const { children, className, decorator, defaultSelected, disabled, helperText, invalid = false, invalidText, labelPosition = "right", legendText, name, onChange = () => {}, orientation = "horizontal", readOnly, valueSelected, warn = false, warnText, slug, required, ...rest } = props;
const prefix = usePrefix();
const [selected, setSelected] = useState(valueSelected ?? defaultSelected);
const prevValueSelected = useRef(valueSelected);
const radioButtonGroupInstanceId = useId();
useEffect(() => {
if (valueSelected !== prevValueSelected.current) {
setSelected(valueSelected);
prevValueSelected.current = valueSelected;
}
}, [valueSelected]);
function getRadioButtons() {
return React.Children.map(children, (radioButton) => {
if (!radioButton) return;
const newProps = {
name,
key: radioButton.props.value,
value: radioButton.props.value,
onChange: handleOnChange,
checked: radioButton.props.value === selected,
required
};
if (!selected && radioButton.props.checked) newProps.checked = true;
return React.cloneElement(radioButton, newProps);
});
}
function handleOnChange(newSelection, value, evt) {
if (!readOnly) {
if (newSelection !== selected) {
setSelected(newSelection);
onChange(newSelection, name, evt);
}
}
}
const showWarning = !readOnly && !disabled && !invalid && warn;
const showHelper = !invalid && !disabled && !warn;
const wrapperClasses = classNames(`${prefix}--form-item`, className);
const fieldsetClasses = classNames(`${prefix}--radio-button-group`, {
[`${prefix}--radio-button-group--${orientation}`]: orientation === "vertical",
[`${prefix}--radio-button-group--label-${labelPosition}`]: labelPosition,
[`${prefix}--radio-button-group--readonly`]: readOnly,
[`${prefix}--radio-button-group--invalid`]: !readOnly && !disabled && invalid,
[`${prefix}--radio-button-group--warning`]: showWarning,
[`${prefix}--radio-button-group--slug`]: slug,
[`${prefix}--radio-button-group--decorator`]: decorator
});
const helperClasses = classNames(`${prefix}--form__helper-text`, { [`${prefix}--form__helper-text--disabled`]: disabled });
const hasHelper = typeof helperText !== "undefined" && helperText !== null;
const helperId = !hasHelper ? void 0 : `radio-button-group-helper-text-${radioButtonGroupInstanceId}`;
const helper = hasHelper && /* @__PURE__ */ jsx("div", {
id: helperId,
className: helperClasses,
children: helperText
});
const divRef = useRef(null);
const candidate = slug ?? decorator;
const normalizedDecorator = isComponentElement(candidate, AILabel) ? cloneElement(candidate, {
size: "mini",
kind: "default"
}) : candidate;
return /* @__PURE__ */ jsxs("div", {
className: wrapperClasses,
ref: mergeRefs(divRef, ref),
children: [
/* @__PURE__ */ jsxs("fieldset", {
className: fieldsetClasses,
disabled,
"data-invalid": invalid ? true : void 0,
"aria-describedby": showHelper && helperText ? helperId : void 0,
...rest,
children: [legendText && /* @__PURE__ */ jsxs(Legend, {
className: `${prefix}--label`,
children: [legendText, slug ? normalizedDecorator : decorator ? /* @__PURE__ */ jsx("div", {
className: `${prefix}--radio-button-group-inner--decorator`,
children: normalizedDecorator
}) : ""]
}), getRadioButtons()]
}),
/* @__PURE__ */ jsxs("div", {
className: `${prefix}--radio-button__validation-msg`,
children: [!readOnly && !disabled && invalid && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(WarningFilled, { className: `${prefix}--radio-button__invalid-icon` }), /* @__PURE__ */ jsx("div", {
className: `${prefix}--form-requirement`,
children: invalidText
})] }), showWarning && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(WarningAltFilled, { className: `${prefix}--radio-button__invalid-icon ${prefix}--radio-button__invalid-icon--warning` }), /* @__PURE__ */ jsx("div", {
className: `${prefix}--form-requirement`,
children: warnText
})] })]
}),
showHelper && helper
]
});
});
RadioButtonGroup.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
decorator: PropTypes.node,
defaultSelected: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
disabled: PropTypes.bool,
helperText: PropTypes.node,
invalid: PropTypes.bool,
invalidText: PropTypes.node,
labelPosition: PropTypes.oneOf(["left", "right"]),
legendText: PropTypes.node,
name: PropTypes.string.isRequired,
onChange: PropTypes.func,
orientation: PropTypes.oneOf(["horizontal", "vertical"]),
readOnly: PropTypes.bool,
required: PropTypes.bool,
slug: deprecate(PropTypes.node, "The `slug` prop has been deprecated and will be removed in the next major version. Use the decorator prop instead."),
valueSelected: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
warn: PropTypes.bool,
warnText: PropTypes.node
};
RadioButtonGroup.displayName = "RadioButtonGroup";
//#endregion
export { RadioButtonGroup as default };