Skip to content

Getting Started

Basic Example

Let's start with a basic example.
Below is a form that asks for a first name, last name and email address.

jsx
import * as React from 'react'
import {FormProvider, useCreateForm, useFormField, useFormInstance, useSubmitHandler} from '@formulier/react'

export default function Example() {
	const form = useCreateForm({
		initialValues: {
			firstName: '',
			lastName: '',
			email: '',
		},
	})

	const onSubmit = useSubmitHandler(form, values => {
		alert(JSON.stringify(values, null, 2))
	})

	return (
		<form onSubmit={onSubmit}>
			<FormProvider form={form}>
				<InputField name="firstName" label="First name" />
				<InputField name="lastName" label="Last name" />
				<InputField name="email" label="Email" type="email" />

				<button type="submit">Submit</button>
			</FormProvider>
		</form>
	)
}

function InputField({name, label, type = 'text'}) {
	const form = useFormInstance()
	const [field] = useFormField(form, {name})

	return (
		<div className="field">
			<label className="label" htmlFor={name}>
				{label}
			</label>
			<input
				{...field}
				className="input"
				type={type}
				name={name}
				value={field.value || ''}
				onChange={event => field.onChange(event.target.value)}
			/>
		</div>
	)
}
Try it out

Quick Explanation

The first thing we need to set up a form is the useCreateForm hook. This hook creates a form store with initial values for its form fields. This form store contains all the form's data and usefull methods to set values and more.

Then we render the Form component provided by @formulier/react and pass it the form store and a submit handler that's called with the form values when the user submits the form.

The last piece to the puzzle is the useFormField hook. We pass this hook the form store, a name and an optional validator function. useFormField provides us with everything we need to render the input elements for our form.