I am working on a checkbox control.
And this method does not seem to be optimal.
I don’t know if this is the correct usage of react-hook-form.
function App() {
const methods = useForm();
const { setValue, register } = methods;
const cbxOnchange = (e) => {
const { checked } = e.target;
if(!checked)
setValue('cbxall', false);
const cbx1 = document.getElementsByName('cbx1')[0].checked;
const cbx2 = document.getElementsByName('cbx2')[0].checked;
if(cbx1 && cbx2)
setValue('cbxall', true);
};
return (
<>
<div>
<input type='checkbox' {...register('cbxall',{ onChange: (e) => {
setValue('cbx1', e.target.checked);
setValue('cbx2', e.target.checked);
} })} defaultChecked />
<input type='checkbox' {...register('cbx1',{ onChange: cbxOnchange })} defaultChecked />
<input type='checkbox' {...register('cbx2',{ onChange: cbxOnchange })} defaultChecked />
</div>
</>
)
}
Please, somebody help me.
2
Answers
I do not understand deeply what you need. If you want to clean up the code a little bit you can use the
event.target.name
andevent.target.checked
.Something like:
Here are some optimizations that can be made:
Controller
component from react-hook-form, which provides better integration with the form state.default values
for all checkboxes, ensuring a consistent initial state.watch
function to observe changes incbx1
andcbx2
, which allows to updatecbxall
reactively.useEffect
hook is used to updatecbxall
whenevercbx1
orcbx2
change, eliminating the need for manual DOM manipulation.handleAllChange
function is simplified and only handles updatingcbx1
andcbx2
whencbxall
changes.Controller
, which provides better control over the input and its interactions with the form state.import React from ‘react’;
import { useForm, Controller } from ‘react-hook-form’;