Skip to Content

react-hook-form

Use a generated schema as a resolver, and convert the input values.

The repository has a complete app in examples/react-forms. Its react-hook-form version is in src/forms/ReactHookForm.tsx.

Resolver

Pass the generated schema to the resolver of the library.

import { valibotResolver } from "@hookform/resolvers/valibot";
import type { MessageInitShape } from "@bufbuild/protobuf";
import { useForm } from "react-hook-form";
import { CreateUserRequestSchema } from "./gen/example/v1/user_pb";
import {
  type CreateUserRequestInput,
  CreateUserRequestValidationSchema,
} from "./gen/example/v1/user_pvschema";

type FormOutput = MessageInitShape<typeof CreateUserRequestSchema>;

const form = useForm<CreateUserRequestInput, unknown, FormOutput>({
  resolver: valibotResolver(CreateUserRequestValidationSchema),
});

For Zod, use zodResolver from @hookform/resolvers/zod. It accepts the output of lib=zod and of lib=zod-mini.

Submit

The validated value is the init shape of the message.

const onSubmit = form.handleSubmit((values) => {
  const request = create(CreateUserRequestSchema, values);
});

Convert the input values

An <input> holds a string, and a schema expects the type that protobuf-es uses. Convert with setValueAs. A string that cannot convert stays a string, and the schema reports a type issue for the field.

inputs.ts
export function toOptionalInt(value: string): number | string | undefined {
  if (value === "") {
    return undefined;
  }
  return /^-?[0-9]+$/u.test(value) ? Number(value) : value;
}

export function toBigInt(value: string | bigint): bigint | string {
  if (typeof value === "bigint") {
    return value;
  }
  return /^-?[0-9]+$/u.test(value) ? BigInt(value) : value;
}
<input inputMode="numeric" {...register("age", { setValueAs: toOptionalInt })} />
<input inputMode="numeric" {...register("points", { setValueAs: toBigInt })} />
FieldConversion
int32a number, or undefined for an empty input on an optional field
int64a bigint
enumNumber on the <select> value
repeated stringsplit the input, or use useFieldArray
boolnone, a checkbox gives a boolean

oneof

The value of a oneof is { case, value }. Register the case and the value as two fields.

<select {...register("contact.case", { setValueAs: emptyToUndefined })}>
  <option value="">None</option>
  <option value="phone">Phone</option>
  <option value="slack">Slack</option>
</select>;
{
  contactCase !== undefined && <input {...register("contact.value", { shouldUnregister: true })} />;
}

shouldUnregister removes the value when no case is selected, so the form holds { case: undefined }.

Error paths

An issue path matches the field name that react-hook-form uses, for example tags.1 and contact.value.

<p role="alert">{errors.contact?.value?.message}</p>