React-hook-form v7 - Custom input warning Function components cannot be given refs

Viewed 801

I'm migrating React-Hook-Form from v6 to v7, and I have a little problem with my custom inputs.

Here is the warning of the console at the first call of the custom input: enter image description here

Here is my code of parent (form):

 <form onSubmit={handleSubmit(onSubmit)}>
    <div className="row">
        <div className="md-8">
            <div className="form-group">
                  <Input
                     name="host"
                     label="Adresse host *"
                     error={errors.host}
                     {...register('host')}
                  />
             </div>
        </div> 
    </div>
</form>

And here code of child:

import React from 'react'

type Props = {
    name?:string
    label?: string
    error?: any
    type?: string
    placeholder?: string
    helper?:string
}

const Input: React.FC<Props> = (props) => {

    const {name, label, error, type, placeholder, helper, ...rest} = props

    return(
        <div className="form-group inputText">
            {label && <label htmlFor={name}>{label}</label>}
            <input 
                type={type ?? "text"} 
                name={name}
                placeholder={placeholder ?? ""}
                className={`form-input ${error ? "form-error" : ''}`}
                {...rest}/>
            {!!helper && <small className="input-helper">{helper}</small>}
            {error && <span className="input-error red" style={{marginBottom: 5}}>{error.type === "required" ? "Champs obligatoire" : error.message}</span>}
        </div>
    )
}

export default Input

The form works but the error is bothering me. And I can't remove it despite my fruitless search on the internet...

Thanks a lot !

2 Answers

ok I don't know why I didn't succeed the first time, but by adding a forwardRef to my component the problem disappeared... Like this:

const Input: React.FC<Props> = React.forwardRef((props, ref) => {
   [...]
    <input 
       type={type ?? "text"} 
       name={name}
       placeholder={placeholder ?? ""}
       ref={ref}
       className={`form-input ${error ? "form-error" : ''}`}
       {...rest}/>
   [...]
})

you can merge your refs and then pass it to do it you can either use a third party library like react-merge-refs or simply write the code to do it your self like the code below:

const mergeRefs = (...refs) => {
    return value => {
        refs.forEach(ref => {
            if (typeof ref === 'function') ref(value);
            else if (ref != null) ref.current = value;
        });
    };
};

then you can simply use this function like below

mergeRefs(ref1, ref2);
Related