@rjsf/core
Version:
A simple React component capable of building HTML forms out of a JSON schema.
31 lines (30 loc) • 2.54 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback } from 'react';
import { ariaDescribedByIds, enumOptionsDeselectValue, enumOptionsIsSelected, enumOptionsSelectValue, enumOptionsValueForIndex, optionId, } from '@rjsf/utils';
/** The `CheckboxesWidget` is a widget for rendering checkbox groups.
* It is typically used to represent an array of enums.
*
* @param props - The `WidgetProps` for this component
*/
function CheckboxesWidget({ id, disabled, options: { inline = false, enumOptions, enumDisabled, emptyValue }, value, autofocus = false, readonly, onChange, onBlur, onFocus, }) {
const checkboxesValues = Array.isArray(value) ? value : [value];
const handleBlur = useCallback(({ target }) => onBlur(id, enumOptionsValueForIndex(target && target.value, enumOptions, emptyValue)), [onBlur, id]);
const handleFocus = useCallback(({ target }) => onFocus(id, enumOptionsValueForIndex(target && target.value, enumOptions, emptyValue)), [onFocus, id]);
return (_jsx("div", { className: 'checkboxes', id: id, children: Array.isArray(enumOptions) &&
enumOptions.map((option, index) => {
const checked = enumOptionsIsSelected(option.value, checkboxesValues);
const itemDisabled = Array.isArray(enumDisabled) && enumDisabled.indexOf(option.value) !== -1;
const disabledCls = disabled || itemDisabled || readonly ? 'disabled' : '';
const handleChange = (event) => {
if (event.target.checked) {
onChange(enumOptionsSelectValue(index, checkboxesValues, enumOptions));
}
else {
onChange(enumOptionsDeselectValue(index, checkboxesValues, enumOptions));
}
};
const checkbox = (_jsxs("span", { children: [_jsx("input", { type: 'checkbox', id: optionId(id, index), name: id, checked: checked, value: String(index), disabled: disabled || itemDisabled || readonly, autoFocus: autofocus && index === 0, onChange: handleChange, onBlur: handleBlur, onFocus: handleFocus, "aria-describedby": ariaDescribedByIds(id) }), _jsx("span", { children: option.label })] }));
return inline ? (_jsx("label", { className: `checkbox-inline ${disabledCls}`, children: checkbox }, index)) : (_jsx("div", { className: `checkbox ${disabledCls}`, children: _jsx("label", { children: checkbox }) }, index));
}) }));
}
export default CheckboxesWidget;