Form
The <Form>
component acts as a container for a set of fields, enabling data transmission to a server. It operates like a standard HTML form, initiating either a request based on the specified method
attribute.
Additionally, the <Form>
allows to validate user input and offers feedback for incorrect data entries, enhancing the overall resilience and user-friendliness of the form submission process. See the Validation guide to learn more about form validation.
Import
import { Form } from '@marigold/components';
Appearance
Property | Type | Description |
---|---|---|
variant | - | The available variants of this component. |
size | - | The available sizes of this component. |
Props
action?
string | ((formData: FormData) => void | Promise<void>);
aria-describedby?
string;
aria-details?
string;
aria-label?
string;
aria-labelledby?
string;
autoCapitalize?
"off" | "on" | "none" | "sentences" | "words" | "characters";
autoComplete?
"off" | "on";
children?
ReactNode;
encType?
"application/x-www-form-urlencoded" | "multipart/form-data" | "text/plain";
id?
string;
maxWidth?
0 | "auto" | "full" | "fit" | "min" | "max" | "screen" | "svh" | "lvh" | "dvh" | "px" | "0.5" | 1 | "1.5" | 2 | "2.5" | 3 | "3.5" | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 14 | 16 | 20 | 24 | 28 | ... 37 more ...
"full"
method?
"get" | "post" | "dialog";
onInvalid?
(event: FormEvent<HTMLFormElement>) => void;
onReset?
(event: FormEvent<HTMLFormElement>) => void;
onSubmit?
(event: FormEvent<HTMLFormElement>) => void;
role?
"search" | "presentation";
target?
"_blank" | "_self" | "_parent" | "_top";
unstyled?
boolean;
validationBehavior?
"aria" | "native";
'native'
validationErrors?
ValidationErrors;
Examples
Setup
This is a simple setup how to use a <Form>
.
Handling submission
The onSubmit
event is useful for custom form actions, such as calling a REST API, instead of relying on the native form submission. It triggeres when a user submits the form using the Enter key or clicks the submit button. The onReset
event is triggered when a user presses a reset button ([type=reset]
).
Server Errors
The <Form>
component handles passed errors, typically received from a server after form submission. To display validation errors, set the validationErrors
prop as an object mapping each field's name prop to a string or array of strings representing errors. These errors appear to the user as soon as the validationErrors
prop is set and are cleared when the user modifies the corresponding field's value.
For more information about form validation, see the Validation guide.
Focus Management
As you can see in the previous server errors example, when a user submits a form with validation errors, the first invalid field is automatically focused. This behavior can be customized using e.preventDefault
during the onInvalid
event and manage the focus manually.
You can find more examples and usages of the <Form>
component on the Validation page and in the Forms recipes.