Marigold
v17.9.1
Marigold
v17.9.1

Application

MarigoldProvider
RouterProvider

Layout

AppLayoutbeta
Aside
Aspect
Breakout
Center
Columns
Container
Grid
Inline
Inset
Scrollable
Split
Stack
Tiles

Actions

ActionBaralpha
Button
Link
LinkButton
ToggleButtonbeta

Form

Autocomplete
Calendar
Checkbox
ComboBox
DateField
DatePicker
DateRangePickerbeta
FileField
Form
Multiselectdeprecated
NumberField
Radio
RangeCalendaralpha
SearchField
Select
Slider
Switch
TagFieldbeta
TextArea
TextField
TimeField

Collection

SelectList
Table
Tag

Navigation

Accordion
Breadcrumbs
Pagination
Sidebarbeta
Tabs
TopNavigationbeta

Overlay

ContextualHelp
Dialog
Drawer
Menu
Toastbeta
Tooltip

Content

Badge
Card
Divider
EmptyStatebeta
Headline
Icon
List
Loader
SectionMessage
SVG
Text

Formatters

DateFormat
NumericFormat

Hooks and Utils

cn
cva
extendTheme
parseFormData
useAsyncListData
useListData
useResponsiveValue
useTheme
VisuallyHidden
Components

Form

Wrap your fields to submit user data and enable input validation.

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

PropertyTypeDescription
variant-The available variants of this component.
size-The available sizes of this component.

Props

Form

Prop

Type

Accessibility props (5)

Prop

Type

DOM event handlers (64)

Prop

Type

Examples

Setup

This is a simple setup how to use a <Form>.

import { Button, Form, Inset, Stack, TextField } from '@marigold/components';export default () => {  return (    <Form>      <Inset space={8}>        <Stack space={2} alignX="left">          <TextField label="User Name" name="user" type="name" width="1/2" />          <TextField            label="Password"            name="password"            type="password"            width="1/2"          />          <Button variant="primary" type="submit">            Login          </Button>        </Stack>      </Inset>    </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]).

import { useState } from 'react';import {  Button,  Form,  Inline,  Inset,  Stack,  Text,  TextField,} from '@marigold/components';export default () => {  let [action, setAction] = useState<string | null>(null);  return (    <Form      onSubmit={e => {        // This will prevent the native form submission        e.preventDefault();        // Read the form values and convert it to a regular object        const data = Object.fromEntries(new FormData(e.currentTarget));        setAction(`data: ${JSON.stringify(data, null, 2)}`);      }}      onReset={() => setAction('reset')}    >      <Inset space={8}>        <Stack space={4}>          <Stack space={2} alignX="left">            <TextField              label="User Name"              name="user"              type="name"              width="1/2"              required            />            <TextField              label="Password"              name="password"              type="password"              width="1/2"              required            />            <Inline space={2}>              <Button variant="primary" type="submit">                Login              </Button>              <Button type="reset">Reset</Button>            </Inline>          </Stack>          {action && (            <div className="bg-secondary-200 rounded-lg p-4">              <Text weight="bold">Action:</Text>              <pre>                <code>{action}</code>              </pre>            </div>          )}        </Stack>      </Inset>    </Form>  );};

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.

Incorrect password.
import { Button, Form, Inset, Stack, TextField } from '@marigold/components';export default () => {  return (    <Form validationErrors={{ password: 'Incorrect password.' }}>      <Inset space={8}>        <Stack space={2} alignX="left">          <TextField label="User Name" name="user" type="name" width="1/2" />          <TextField            label="Password"            name="password"            type="password"            width="1/2"          />          <Button variant="primary" type="submit">            Login          </Button>        </Stack>      </Inset>    </Form>  );};

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.

import { useState } from 'react';import {  Button,  Form,  Inline,  Inset,  SectionMessage,  Stack,  TextField,} from '@marigold/components';export default () => {  let [invalid, setInvalid] = useState(false);  return (    <Form      onInvalid={e => {        e.preventDefault();        setInvalid(true);      }}      onSubmit={e => {        e.preventDefault();        setInvalid(false);      }}      onReset={() => setInvalid(false)}    >      <Inset space={8}>        <Stack space={4}>          {invalid ? (            <SectionMessage variant="error">              <SectionMessage.Title>Whoopsies!</SectionMessage.Title>              <SectionMessage.Content>                Please enter both your email address and password to proceed.                Ensure that all required fields are filled correctly before                attempting to log in.              </SectionMessage.Content>            </SectionMessage>          ) : null}          <Stack space={2} alignX="left">            <TextField              label="User Name"              name="user"              type="name"              width="1/2"              required            />            <TextField              label="Password"              name="password"              type="password"              width="1/2"              required            />            <Inline space={2}>              <Button variant="primary" type="submit">                Login              </Button>              <Button type="reset">Reset</Button>            </Inline>          </Stack>        </Stack>      </Inset>    </Form>  );};

Want more?!

You can find more examples and usages of the <Form> component on the Validation page.

Last update: 4 months ago

FileField

A form component for uploading files with drag and drop support.

Multiselect

A text-field that allows the user to select multiples values from a provided items array.

On this page

ImportAppearancePropsFormExamplesSetupHandling submissionServer ErrorsFocus Management