0

I created a form with reactstrap and react-hook-form. Why are my errors not displaying?

Dummy section which renders text input:

function DummySection() {
  const { control } = useForm();
  return (
    <div>
      <Controller
        name="dummyName"
        control={control}
        rules={{ required: true }}
        defaultValue=""
        render={({ field: { onChange, ref }, fieldState: { error } }) => (
          <TextInput onChange={onChange} innerRef={ref} error={error} />
        )}
      />
    </div>
  );
}

Text input with error:

function TextInput({ onChange, value, innerRef, error }) {
  const updateText = (e) => {
    onChange(e);
    // do something else below
  };
  return (
    <div>
      <Input
        name="dummyName"
        type="text"
        onChange={(e) => updateText(e)}
        value={value}
        innerRef={innerRef}
      />
      {error && "Cannot be blank"}
    </div>
  );
}

Submit Button

function SubmitBtn() {
  const { handleSubmit } = useForm();
  const onSubmit = (data) => console.log(data);

  return <Button onClick={() => handleSubmit(onSubmit)()}>Submit</Button>;
}

Thanks.

Code Sandbox

1 Answer 1

1

@jamfie, you are using different useForm for each component.

Your form need to have the same instance, you can do that by using useformcontext or by passing props to components.

Also, you do not need Controller for this thing, here is codesandbox shows how you can use reactstrap with react-hook-form.

You can also follow this answer in github issue.

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

1 Comment

Thanks! I need to control the state hence I used Controller. Using useformcontext and ensuring all form components are using the same instance did the job.

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.