gform-react
Back to Introduction

Getting Started

Install gform-react, wire up peer dependencies, and build your first validated form.

Installation

Install the package with your preferred package manager:

npm install gform-react
yarn add gform-react
pnpm add gform-react

Peer dependencies

gform-react relies on React as a peer dependency:

PackageVersion
react>=18.0.0
react-dom>=18.0.0

React 18+ is required because the form store is built on useSyncExternalStore - the same mechanism that powers gform-react's minimal re-renders.

Your first form

A gform-react form is made of three pieces:

  1. A typed interface describing your form - keys are field names, values are field value types.
  2. A validators object (kept at module level for a stable reference).
  3. GForm wrapping one or more GInput fields, each rendered through an element render prop.
SignIn.tsx
import { GForm, GInput, GValidator, type GValidators } from "gform-react";
 
interface SignInForm {
  username: string;
  password: string;
}
 
// '*' is the default validator applied to every field.
const baseValidator = new GValidator().withRequiredMessage("This field is required");
 
const validators: GValidators<SignInForm> = {
  "*": baseValidator,
  password: new GValidator(baseValidator).withMinLengthMessage(
    (input) => `${input.formKey} must contain at least ${input.minLength} characters`
  ),
};
 
export default function SignIn() {
  return (
    <GForm<SignInForm>
      validators={validators}
      onSubmit={(state, e) => {
        e.preventDefault(); // gform does NOT auto-preventDefault
        console.log(state.toRawData()); // { username, password }
      }}
    >
      <GInput
        formKey="username"
        required
        element={(input, props) => (
          <div>
            <input {...props} placeholder="username" />
            {input.error && <small className="error">{input.errorText}</small>}
          </div>
        )}
      />
      <GInput
        formKey="password"
        type="password"
        required
        minLength={5}
        element={(input, props) => (
          <div>
            <input {...props} placeholder="password" />
            {input.error && <small className="error">{input.errorText}</small>}
          </div>
        )}
      />
      <button>Sign in</button>
    </GForm>
  );
}

Try it live

Edit the code below - it runs against the published gform-react package:

Loading playground…
The submit button

A native <button> inside GForm submits the form by default - you don't need type="submit". If you use a custom button component (which usually defaults to type="button"), you must pass type="submit" explicitly.

Next steps