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-reactyarn add gform-reactpnpm add gform-reactPeer dependencies
gform-react relies on React as a peer dependency:
| Package | Version |
|---|---|
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:
- A typed interface describing your form - keys are field names, values are field value types.
- A
validatorsobject (kept at module level for a stable reference). GFormwrapping one or moreGInputfields, each rendered through anelementrender prop.
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
- Core Concepts - understand
formKey, theelementrender prop, and form state. - Validation - go deeper on native, custom, and async validation.
- Examples & Playground - explore complete, runnable forms.