I’ve recently tried to switch from Multiselect dropdown to checkboxes instead in react and replicate a similar behavior to the previous Multiselect dropdown that I used.
But I’m struggling to get the checkbox value (error: Uncaught TypeError: Cannot read properties of undefined (reading ‘value’)) and store the checked values. Please advise what I could be missing?
Here is how my multiselect was setup before and the checkbox component and functions I currently have:
import { Multiselect } from 'multiselect-react-dropdown';
// Get Alert Filters
const [alertTypeFilter, setAlertTypeFilter] = useState([]);
const [isSelectedList, setIsSelectedList] = useState([]);
alertTypes = alertTypes.map((alertType) => ({
value: alertType.id,
name: alertType.description,
}));
//Old Multiselect replaced by checkbox component below it:
<Multiselect
options={alertTypes}
displayValue="name"
selectedValues={alertTypeFilter}
closeOnSelect={false}
avoidHighlightFirstOption
placeholder="Select Alert Subtype"
onSelect={(selectedList) => {
alertTypeFilterChangeFunc(selectedList);
}}
onRemove={(selectedList) => {
alertTypeFilterChangeFunc(selectedList);
}}
/>
My checkbox component:
const Checkbox = ({
checboxText, textBold, onClickFunc, checked, labelStyle, testID,
disabled,
}) => {
const checkboxInputRef = useRef();
if (checked === 'indeterminate' && checkboxInputRef.current) {
checkboxInputRef.current.indeterminate = true;
checkboxInputRef.current.checked = false;
} else if (checkboxInputRef.current) {
checkboxInputRef.current.indeterminate = false;
checkboxInputRef.current.checked = checked;
}
return (
<label
className={`checkbox-container ${textBold ? 'bold' : ''} row`}
style={labelStyle}
>
<input
data-test={testID}
checked={checked}
type="checkbox"
onChange={(event) => {
onClickFunc(event.currentTarget.checked);
}}
ref={checkboxInputRef}
disabled={disabled}
/>
<div
className="checkbox-custom"
style={{ marginRight: checboxText ? '10px' : '0' }}
/>
{checboxText}
</label>
);
};
Checkbox.propTypes = {
onClickFunc: PropTypes.func.isRequired,
checked: PropTypes.oneOf([true, false, 'indeterminate']).isRequired,
checboxText: PropTypes.string,
textBold: PropTypes.bool,
labelStyle: PropTypes.any,
testID: PropTypes.string,
disabled: PropTypes.bool,
};
This is how I then rendered the checkbox component:
const handleChange = (event) => {
const { value, checked } = event.target;
const mappedData = isSelectedList.map((selected) => (selected.value === value ? { ...selected, isChecked: checked } : selected));
setIsSelectedList(mappedData);
};
{alertTypes.map((alert) => (
<div key={alert.value}>
<CheckBox
value={alert.name}
name={alert.name}
checboxText={alert.name}
onClickFunc={(event) => handleChange(event)}
/>
</div>
))}