Handle submission
Now your first form is almost ready. There is only one little thing missing and that is the data processing when the form is submitted.
Submit event
To process the values on submission, you need to pass a function to the onSubmit
property of the Form
component. The first parameter passed to the function are the form values and the second is the event object.
Code example
import { SubmitHandler, useForm } from '@modular-forms/react';
type LoginForm = {
email: string;
password: string;
};
export default function App() {
const [loginForm, { Form, Field }] = useForm<LoginForm>();
const handleSubmit: SubmitHandler<LoginForm> = (values, event) => {
// Your code here
};
return <Form onSubmit={handleSubmit}>…</Form>;
}
Prevent default
When the form is submitted, event.preventDefault()
is executed by default to prevent the window from reloading so that the values can also be processed directly in the browser and the state of the form is preserved.
Loading animation
While the form is being submitted, you can use loginForm.submitting
to display a loading animation and disable the submit button.
Only dirty values
Using the shouldDirty
property of the Form
component, you have the option to have the form return only modified values. This reduces network traffic, for example if you only want to update values that have changed in your database.