seti-ramesesv1
Version:
Reusable components and context for Next.js apps
42 lines (39 loc) • 2.1 kB
JavaScript
import { jsx, jsxs } from 'react/jsx-runtime';
import { clsx } from '../../node_modules/clsx/dist/clsx.js';
import { createContext, useState, useId, useEffect, useContext } from 'react';
import styles from '../../styles/Radio.module.css.js';
const RadioGroupContext = createContext(null);
function RadioGroup({ name, value, defaultValue, onChange, direction = "column", disabled, size = "medium", groupLabel, className, children, }) {
const [internalValue, setInternalValue] = useState(defaultValue !== undefined ? String(defaultValue) : undefined);
const isControlled = value !== undefined;
const selectedValue = isControlled ? String(value) : internalValue;
const groupName = name || useId();
const handleChange = (event) => {
const newValue = event.target.value;
if (!isControlled) {
setInternalValue(newValue);
}
onChange?.(newValue);
};
useEffect(() => {
if (!isControlled && defaultValue !== undefined) {
setInternalValue(String(defaultValue));
}
}, [isControlled, defaultValue]);
return (jsx(RadioGroupContext.Provider, { value: {
name: groupName,
selectedValue,
onChange: handleChange,
size,
disabled,
}, children: jsxs("fieldset", { className: clsx(styles.radioGroup, className), "aria-label": groupLabel, children: [groupLabel && (jsx("legend", { className: clsx(styles.radioGroupLegend, size === "small" && styles.radioGroupLegendSmall, size === "medium" && styles.radioGroupLegendMedium, size === "large" && styles.radioGroupLegendLarge), children: groupLabel })), jsx("div", { className: clsx(direction === "column" ? styles.radioGroupDirectionColumn : styles.radioGroupDirectionRow), children: children })] }) }));
}
function useRadioGroupContext() {
const context = useContext(RadioGroupContext);
if (!context) {
throw new Error("Radio must be used within a RadioGroup.");
}
return context;
}
export { RadioGroup as default, useRadioGroupContext };
//# sourceMappingURL=RadioGroup.js.map