Quick start

Installation

npm
yarn
pnpm
bun
deno
npm install react-headless-form react-hook-form

Peer dependencies: react-hook-form ^7.55.0 and react / react-dom ^16.8 || ^17 || ^18 || ^19. Install react-hook-form alongside BlueForm.

Basic usage

Let's start with a simple login form. The form data is represented by the following TypeScript type:

type LoginData = {
  username: string;
  password: string;
};

0. Define a field

import type { InputHTMLAttributes } from "react";
import { useField } from "react-headless-form";

export default function InputField(props: InputHTMLAttributes<HTMLInputElement>) {
  const { value, onChange, onBlur, ref, label, description, errorMessage, required, disabled, readOnly } =
    useField();

  return (
    <div>
      {/* the input inside its label: associated without any id */}
      <label>
        {label} {required && "*"}
        <input
          {...props}
          ref={ref}
          value={value ?? ""}
          onChange={(e) => onChange(e.target.value)}
          onBlur={onBlur}
          disabled={disabled}
          readOnly={readOnly}
          aria-invalid={Boolean(errorMessage)}
        />
      </label>
      {description && <div>{description}</div>}
      {errorMessage && <div role="alert">{errorMessage}</div>}
    </div>
  );
}

Notice that the field receives everything it needs from useField hook to be functional without needing to know where those values come from.

1. Setup the engine

import { setupForm, defineMapping } from "react-headless-form"
import InputField from "./InputField"

export const [Form] = setupForm({
  fieldMapping: defineMapping({
    text: InputField,
  }),
})

2. Build the form

const BasicForm = () => {
  return (
    <Form<LoginData>
      renderRoot={({ children, onSubmit }) => (
        <form onSubmit={onSubmit}>{children}</form>
      )}
      onSubmit={(data) => alert(JSON.stringify(data, null, 2))}
      config={{
        username: {
          type: "text",
          label: "Your name",
          rules: {
            required: "Name is required",
          },
        },
        password: {
          type: "text",
          label: "Password",
          rules: {
            required: "Password is required",
          },
          props: {
            // html input type
            type: "password",
          },
        },
      }}
    >
      <button type="submit">Submit</button>
    </Form>
  );
};

Preview

Preview
Note

The form above is unstyled intentionally. BlueForm is headless. Styling is entirely up to you.

Next steps