Search code examples
reactjsreact-hook-form

React.js onBlur event not being fired when using react-hook-form


react-hook-form works just fine. the problem is when I wanted to attach an onBlur callback on the input field. The onFocus works just fine, but when I take the focus to other input fields or anywhere else, the onBlur event is not fired.

When I removed the register feature from react-hook-form onBlur works just fine, but is not fired when I use register from react-hook-form.

...

"react-hook-form": "^7.41.1",

"react": "^18.2.0"

...

here is the first component in the form

< div className="pb-5">
    < label
        className="block text-sm font-medium mb-1"
        htmlFor="name">
        Name <span className="text-rose-500">*</span>
    < /label>
    <input
        id="name"
        className="form-input w-full ml-2 "
        type="text"
        defaultValue={projectState.project.app.name ?? '-'}
        name="name"
        onFocus={() => {
            console.log('got focus')
        }}
        onBlur={(event) => {
            console.log('lost focus')
        }}
        {...register('name', {
                required: {value: true, message: "Name  is required"},
            },
        )}
    />
    {errors.name && <p className={`ml-2 mt-1 text-red-600`}>
        <span>{errors.name.message}</span>
    </p>}
</div>

I tried to attach a callback to an onBlur event. The event is fired when not using react-hook-form. The onBlur event is not being fired when I am using react-hook-form, only the onFocus is fired


Solution

  • register function overrides value, name, onChange, and onBlur props

    To add logic to onBlur:

    
    const {onBlur, ...fieldProps} = register('name', {
       required: {value: true, message: "Name  is required"},
    })
    
    return (
         // ...
         <input
            id="name"
            className="form-input w-full ml-2 "
            type="text"
            onFocus={() => {
                console.log('got focus')
            }}
            onBlur={(event) => {
                console.log('lost focus')
                onBlur()
            }}
            {...fieldProps}
        />
        // ...
      )
    
    

    Reference