UNPKG

@nami-ui/radio

Version:
29 lines (28 loc) 1.34 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { useMemo } from 'react'; import clsx from 'clsx'; import { noop, useValue } from '@nami-ui/utils'; import { Stack } from '@nami-ui/stack'; import { RadioGroupContext } from './radio-group-context'; import './radio-group.css'; export function RadioGroup({ value, defaultValue, onChange = noop, disabled = false, direction = 'horizontal', className, children, ...otherProps }) { const [val, setVal, controlled] = useValue(value, defaultValue, null); const context = useMemo(() => { function isChecked(value) { return value === val; } function change(value, check) { const checked = isChecked(value); if (check !== checked) { const newVal = check ? value : null; if (!controlled) { setVal(newVal); } onChange(newVal); } } return { disabled, isChecked, change }; }, [val, disabled]); className = clsx('nami-radio-group', className); return (_jsx(Stack, Object.assign({ direction: direction, spacing: direction === 'horizontal' ? 'big' : true, wrap: true }, otherProps, { children: _jsx(RadioGroupContext.Provider, Object.assign({ value: context }, { children: children }), void 0) }), void 0)); }