1

when I just use <input {...register(name)} />, validation works correctly: empty required-fields give an error, when filled out, the error disappears. But if this input is moved to a separate component, does the error disappear when filled in?

Code:

parent:

<InputField
    validationType="underlineText"
    invalidText={errors?.[name]?.message}
    invalid={Boolean(errors?.[name]?.message)}
    {...register(name)}
/>

InputField.tsx:

export const InputField = memo(({
  invalid,
  invalidText,
  validationType,
  ...otherProps
}: IInputProps) => (
  <InputValidationWrapper
    invalid={invalid}
    invalidText={invalidText}
    validationType={validationType}
  >
    <input
      {...otherProps}
    />
  </InputValidationWrapper>
))
1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented May 25, 2022 at 12:03

1 Answer 1

1

Since react-hook-for works with the ref of element, You need to wrap your custom component with React.forwardRef, like this:

const InputFieldRef = forwardRef(
  ({ invalid, invalidText, validationType, ...otherProps }, ref) => {
    return (
      <InputValidationWrapper
        invalid={invalid}
        invalidText={invalidText}
        validationType={validationType}
      >
        <input {...otherProps} ref={ref} />
      </InputValidationWrapper>
    );
  }
);

export const InputField = memo(InputFieldRef);

and here is example of using above component:

<InputField
        validationType="underlineText"
        invalidText={errors?.[name]?.message}
        invalid={Boolean(errors?.[name]?.message)}
        {...register(name, { required: "Field is Required" })}
/>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.