@chayns-components/core
Version:
A set of beautiful React components for developing your own applications with chayns.
62 lines • 2.32 kB
JavaScript
import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useState } from 'react';
import { getRadioButtonOrder } from '../../../utils/radioButton';
export const RadioButtonGroupContext = /*#__PURE__*/React.createContext({
selectedRadioButtonId: undefined,
updateSelectedRadioButtonId: undefined,
radioButtonsCanBeUnchecked: false,
radioButtonRightElements: [],
updateHasRightElement: undefined
});
RadioButtonGroupContext.displayName = 'RadioButtonGroupContext';
const RadioButtonGroup = /*#__PURE__*/forwardRef((_ref, ref) => {
let {
children,
canUncheckRadioButtons,
selectedId,
onSelect
} = _ref;
const [selectedRadioButtonId, setSelectedRadioButtonId] = useState(undefined);
const [radioButtonRightElements, setRadioButtonRightElements] = useState([]);
const isControlled = typeof selectedId === 'string';
useEffect(() => {
setSelectedRadioButtonId(selectedId);
}, [selectedId]);
const updateSelectedRadioButtonId = useCallback(id => {
if (typeof onSelect === 'function') {
onSelect(id);
}
if (!isControlled) {
setSelectedRadioButtonId(id);
}
}, [isControlled, onSelect]);
const updateHasRightElement = useCallback((id, hasRightElement) => {
setRadioButtonRightElements(prevState => prevState.map(prev => id === prev.id ? {
id,
hasRightElement
} : prev));
}, []);
useEffect(() => {
const ids = getRadioButtonOrder(children);
const rightElements = ids.map(id => ({
id,
hasRightElement: false
}));
setRadioButtonRightElements(rightElements);
}, [children]);
useImperativeHandle(ref, () => ({
updateSelectedRadioButtonId
}), [updateSelectedRadioButtonId]);
const providerValue = useMemo(() => ({
selectedRadioButtonId,
updateSelectedRadioButtonId,
radioButtonsCanBeUnchecked: canUncheckRadioButtons,
updateHasRightElement,
radioButtonRightElements
}), [canUncheckRadioButtons, radioButtonRightElements, selectedRadioButtonId, updateHasRightElement, updateSelectedRadioButtonId]);
return /*#__PURE__*/React.createElement(RadioButtonGroupContext.Provider, {
value: providerValue
}, children);
});
RadioButtonGroup.displayName = 'RadioButtonGroup';
export default RadioButtonGroup;
//# sourceMappingURL=RadioButtonGroup.js.map