Components
Form
A native form element with consolidated error handling.
Anatomy#
Form is composed together with Field. Import the components and place them together:
import { Field } from '@egoist/solid-base/field';
import { Form } from '@egoist/solid-base/form';
<Form>
<Field.Root>
<Field.Label />
<Field.Control />
<Field.Error />
</Field.Root>
</Form>;Examples#
Submit with an action#
Wrap the submission in a Solid action to coordinate it as a
transition. A createOptimistic(false) flag set inside the action reads true while it runs and
reverts once it settles, which is all a pending button needs. Pass the errors the server returns
to errors; each one is shown by the <Field.Error> of the field with the matching name.
Submit form values as a JavaScript object#
You can use onFormSubmit instead of the native onSubmit to access form values as a JavaScript
object. This is useful when you need to transform the values before submission, or integrate with
3rd party APIs.
<Form
onFormSubmit={async (formValues: { id: string; quantity: number }) => {
const payload = {
product_id: formValues.id,
order_quantity: formValues.quantity,
};
const response = await fetch('https://api.example.com', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
}}
/>When used, preventDefault is called on the native submit event.
Using with Zod#
When parsing the schema using schema.safeParse(), the z.flattenError(result.error).fieldErrors
data can be used to map the errors to each field's name:
import { z } from 'zod';
const schema = z.object({
name: z.string().min(1, 'Name is required'),
age: z.coerce.number('Age must be a number').positive('Age must be a positive number'),
});
async function submitForm(formValues: Form.Values) {
const result = schema.safeParse(formValues);
if (!result.success) {
return { errors: z.flattenError(result.error).fieldErrors };
}
return { errors: {} };
}
const [errors, setErrors] = createSignal({});
<Form
errors={errors()}
onFormSubmit={async (formValues) => {
const response = await submitForm(formValues);
setErrors(response.errors);
}}
>
<Field.Root name="name">
<Field.Label>Name</Field.Label>
<Field.Control placeholder="Enter name" />
<Field.Error />
</Field.Root>
<Field.Root name="age">
<Field.Label>Age</Field.Label>
<Field.Control placeholder="Enter age" />
<Field.Error />
</Field.Root>
<Button type="submit">Submit</Button>
</Form>;The live demo below swaps Zod for a small hand-written parser that returns the same
fieldErrors shape, so the docs don't depend on Zod:
API reference#
<Form>
A native form element with consolidated error handling. Renders a <form> element.
validationModeFormValidationMode'onSubmit'Determines when the form should be validated. The validationMode prop on <Field.Root> takes precedence over this.
- onSubmit (default): validates the field when the form is submitted, afterwards fields will re-validate on change. - onBlur: validates a field when it loses focus. - onChange: validates the field on every change to its value.
errorsErrors—Validation errors returned externally, typically after submission by a server or a form action. This should be an object where keys correspond to the name attribute on <Field.Root>, and values correspond to error(s) related to that field.
onFormSubmit| ((formValues: FormValues, eventDetails: Form.SubmitEventDetails) => void)—Event handler called when the form is submitted. preventDefault() is called on the native submit event when used.
actionsRefActionsRef<Form.Actions>—A ref to imperative actions (a { current } object or a callback). - validate: Validates all fields when called. Optionally pass a field name to validate a single field.
classstring | ClassValue | ((state: State) => ClassValue)—CSS class applied to the element, or a function that returns a class based on the component's state.
styleJSX.CSSProperties | string | ((state: State) => JSX.CSSProperties | string)—Style applied to the element, or a function that returns a style based on the component's state.
renderkeyof JSX.IntrinsicElements | ((props: HTMLProps, state: State) => JSX.Element)—Allows you to replace the component's HTML element with a different tag, or compose it with another component.
Accepts a tag name, or a function that receives the props to spread and the component's state, and returns the element to render.