@talend/react-components
Version:
Set of react components.
81 lines (80 loc) • 2.4 kB
JavaScript
import PropTypes from 'prop-types';
import { randomUUID } from '@talend/utils';
import { getTheme } from '../../theme';
import css from './LabelToggle.module.scss';
import { get } from "lodash";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const theme = getTheme(css);
const getAutoFocusValue = (autoFocus, values, value) => {
if (!autoFocus) {
return null;
}
if (value) {
return get(value, 'value');
}
return get(values, ['0', 'value']);
};
/**
*
* @param {Array.<Object>} values - buttons that should be rendered
* @param {string} name - the name attribute for all inputs
* @param {string} value - the checked value
* @param {function} onChange - callback that handle the state change
*/
function LabelToggle({
id,
values,
name,
value,
onChange,
disabled,
autoFocus = false
}) {
const localId = id || randomUUID();
const handleChange = e => {
onChange(e.target.value);
};
const getButtonId = currentValue => `${localId}-radio-${currentValue}`;
const autoFocusValue = getAutoFocusValue(autoFocus, values, value);
return /*#__PURE__*/_jsx("div", {
className: theme('tc-label-toggle', {
'tc-radio-disabled': disabled
}),
children: values.map(button => /*#__PURE__*/_jsxs("label", {
"data-feature": button.dataFeature,
htmlFor: getButtonId(button.value),
className: theme({
'tc-radio-selected': value === button.value
}),
children: [/*#__PURE__*/_jsx("input", {
id: getButtonId(button.value),
type: "radio",
value: button.value,
checked: value === button.value,
name: name,
disabled: disabled,
onChange: e => handleChange(e)
// eslint-disable-next-line jsx-a11y/no-autofocus
,
autoFocus: autoFocusValue === button.value
}), /*#__PURE__*/_jsx("span", {
children: button.label
})]
}, button.value))
});
}
LabelToggle.propTypes = {
autoFocus: PropTypes.bool,
disabled: PropTypes.bool,
id: PropTypes.string,
name: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
value: PropTypes.string,
values: PropTypes.arrayOf(PropTypes.shape({
value: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
dataFeature: PropTypes.string
}).isRequired)
};
export default LabelToggle;
//# sourceMappingURL=LabelToggle.component.js.map