I am building webapp using React and react-hook-form library. I would like to create form where change of some field triggers some event. So I need pass custom onChange
However, since v7.0 I can't use onChange
because register
uses its own onChange
.
import React from 'react'
import { useForm } from 'react-hook-form'
const MyForm = () => {
const form = useForm()
const onChangeFirst = value => console.log('First:', value)
const onChangeSecond = value => console.log('Second:', value)
return (
<form onSubmit={form.handleSubmit(vals => null)}>
<input {...register('first')} />
<input {...register('second')} />
</form>
)
}
How can I pass onChangeFirst
to first
input and onChangeSecond
to second
input?
There are two ways to trigger onChange
while input change.
1/ With Controller component (recommend)
const onChangeFirst = value => console.log('First:', value)
<Controller
control={control}
name="first"
render={({field}) => (
<input {...field} onChange={e => {
onChangeFirst(field.value);
field.onChange(e);
}} />
)}
/>
2/ With useWatch hook
const second = useWatch({
control,
name: 'second'
});
useEffect(() => {
console.log('Second:', second)
}, [second])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With