@carbon/react
Version:
React components for the Carbon Design System
80 lines (78 loc) • 2.92 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 { noopFn } from "../../internal/noopFn.js";
import { isComponentElement } from "../../internal/utils.js";
import RadioTile_default from "../RadioTile/index.js";
import { Children, cloneElement, createElement, isValidElement, useEffect, useState } from "react";
import PropTypes from "prop-types";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
//#region src/components/TileGroup/TileGroup.tsx
/**
* 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.
*/
const TileGroup = ({ children, className, defaultSelected, disabled, legend, name, onChange = noopFn, valueSelected, required }) => {
const prefix = usePrefix();
const [selected, setSelected] = useState(valueSelected ?? defaultSelected);
useEffect(() => {
if (typeof valueSelected !== "undefined" && valueSelected !== selected) setSelected(valueSelected);
}, [valueSelected, selected]);
const handleChange = (value, name, evt) => {
if (value !== selected) {
setSelected(value);
onChange(value, name ?? "", evt);
}
};
const getRadioTilesWithWrappers = (elements) => {
const traverseAndModifyChildren = (elements) => {
return Children.map(elements, (child) => {
if (!isValidElement(child)) return child;
if (isComponentElement(child, RadioTile_default)) {
const { value, ...otherProps } = child.props;
return /* @__PURE__ */ createElement(RadioTile_default, {
...otherProps,
required,
name,
key: value,
value,
onChange: handleChange,
checked: value === selected
});
}
const children = child.props.children;
if (Children.count(children) > 0) return cloneElement(child, void 0, traverseAndModifyChildren(children));
return child;
});
};
return /* @__PURE__ */ jsx(Fragment, { children: traverseAndModifyChildren(elements) });
};
return /* @__PURE__ */ jsxs("fieldset", {
className: className ?? `${prefix}--tile-group`,
disabled,
children: [legend && /* @__PURE__ */ jsx("legend", {
className: `${prefix}--label`,
children: legend
}), /* @__PURE__ */ jsx("div", { children: getRadioTilesWithWrappers(children) })]
});
};
TileGroup.displayName = "TileGroup";
TileGroup.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
defaultSelected: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
disabled: PropTypes.bool,
legend: PropTypes.string,
name: PropTypes.string.isRequired,
onChange: PropTypes.func,
required: PropTypes.bool,
valueSelected: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};
//#endregion
export { TileGroup };