Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onChange input in react-hook-form

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?

like image 827
Michal Avatar asked Jan 24 '23 08:01

Michal


1 Answers

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])
like image 172
nghiepit Avatar answered Jan 31 '23 20:01

nghiepit