4

I'd like to access to the validation rules defined in react-hook-form's Resister in the nested component to dynamically display required indicator(*). Is there a way to access from Nested component?

I don't want to repeat by passing as a prop.

<TextBox ref={register({ required: true })} label="Serial No" name="serialNo" />

const TextBox = React.forwardRef(({ label, name }, ref) => (
    <>
        <label htmlFor={name}>
            {label} {***required*** && <span>*</span>}
        </label>
        <input type="text" name={name} id={name} ref={ref} />
    </>
))

1 Answer 1

4

have a look at https://react-hook-form.com/api#useFormContext

import React from "react";
import { useForm, FormProvider, useFormContext } from "react-hook-form";

export default function App() {
  const methods = useForm();
  const onSubmit = data => console.log(data);

  return (
    <FormProvider {...methods} > // pass all methods into the context
      <form onSubmit={methods.handleSubmit(onSubmit)}>
        <NestedInput />
        <input type="submit" />
      </form>
    </FormProvider>
  );
}

function NestedInput() {
  const { register } = useFormContext(); // retrieve all hook methods
  return <input name="test" ref={register} />;
}

which allow you to access all hook form methods in the nested component level.

Sign up to request clarification or add additional context in comments.

2 Comments

That doesn't answer the question, how can we display the "*" indicator for required field ?
Is there a solution to this problem?

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.