Skip to main content

Getting started

Installation

First install the package with:

# npm
npm install @per-form/react
# yarn
yarn add @per-form/react
# pnpm
pnpm install @per-form/react

Usage

@per-form/react can be used with two main flavors:

With the useForm hook

Use the useForm hook combined with a native HTML <form> component:

0
import type { FormEvent } from 'react';
import { type IFormValues, useForm } from '@per-form/react';

export default function Demo() {
function handleSubmit(_e: FormEvent<HTMLFormElement>, values: IFormValues) {
console.log(values);
}

const { formProps } = useForm({
onSubmit: handleSubmit,
});

return (
<form {...formProps}>
<input name="text" required />
<button type="submit">Submit</button>
</form>
);
}

Easy isn't it ?

tip

You want the input to be at least 3 characters ?

Then just add minlength="3" as you would do in classic HTML and it's done.

All native HTML validations are supported out of the box !

With the <Form> component

Use the <Form> component like the native HTML <form> component:

0
import type { FormEvent } from 'react';
import { Form, type IFormValues } from '@per-form/react';

export default function Demo() {
function handleSubmit(_e: FormEvent<HTMLFormElement>, values: IFormValues) {
console.log(values);
}

return (
<Form onSubmit={handleSubmit}>
<input name="text" required />
<button type="submit">Submit</button>
</Form>
);
}

And that's it !

info

For both cases there is no need to register the form fields, you only need to add a name attribute !

Customize error display

By default @per-form/react use native form validation, but you can also choose to customize the error as you want by setting useNativeValidation: false and display the error as you want :

0
import type { FormEvent } from 'react';
import { type IFormValues, useForm } from '@per-form/react';

export default function Demo() {
function handleSubmit(_e: FormEvent<HTMLFormElement>, values: IFormValues) {
console.log(values);
}

const { errors, formProps } = useForm({
onSubmit: handleSubmit,
useNativeValidation: false,
});

return (
<form {...formProps}>
<input name="text" required />
{errors.all.text && <div className="error">{errors.all.text}</div>}
<button type="submit">Submit</button>
</form>
);
}

Check the guide page about errors for more information.