react-hook-form: v7 register forward refs failed with nested components

Describe the bug register forward refs failed while nesting components.

Expected behavior ref to be created properly with the spread operator

Screenshots image

Desktop (please complete the following information):

  • OS: Windows
  • Browser chrome
  • Version 89

Additional context I have the following components.

export const TextField = props => {
  return (
    <input
      type={props.type}
      defaultValue={props.defaultValue}
      value={props.value}
      name={props.name}
      placeholder={props.placeholder}
      onChange={props.onChange}
      maxLength={props.maxLength}
      className={`input ${props.variant}`}
      spellCheck={false}
      {...props}
    />
  )
}

TextField.defaultProps = {
  variant: 'default',
  maxLength: 99
}
// FormField
export const FormField = props => {
  // access context from FormProvider
  const { register, formState: { errors } } = useFormContext();
  const field_errors = get(errors, props.name);

  return (
    <div className="formField-wrapper">
      <div className="header">
        <label className={`label ${field_errors && 'errors'}`} htmlFor={props.name}>{props.label}</label>
        {field_errors && <label className="error-msg errors">{field_errors.message}</label>}
      </div>
      <TextField
        {...register(props.name)}
        variant={field_errors ? `${props.variant} errors` : props.variant}
        type={props.type}
        defaultValue={props.defaultValue}
        value={props.value}
        placeholder={props.placeholder}
        onChange={props.onChange}
        maxLength={props.maxLength}
      />
    </div>
  )
}
FormField.defaultProps = {
  variant: 'default'
}

So here, I would like to register the FormField’s inner TextField component (which has the base HTML input). So I have used the spread operator with FormField and am taking it in the TextField with {...props}

However, I get the error shown in the screenshot and the submit method is not firing after the first time.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 19 (6 by maintainers)

Most upvoted comments

React does not allow for refs to be forwarded on functional components. You can either use React.forwardRef, or you can extract the ref from the register return and pass that into your TextField component with a new prop name.

https://reactjs.org/docs/forwarding-refs.html

I am trying to reproduce in codesandbox, thanks for your time.