Skip to content
Advertisement

Accessing error from react-hook-form using reactstrap

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

Advertisement

Answer

@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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement