Form
A form is a group of inputs that allows users to submit data to a server, with support for providing field validation errors.
Installation
CLI
Manual
npx hq-kit add form
Validation
Preview
Code
Sometimes, server-side errors don't match the client-side validation. You can handle this by using the validationErrors
prop to format them correctly.
<Form validationErrors={errors} onSubmit={() => {}} />
Then, in the <TextField />
component, pass the errorMessage
prop like this:
<TextField errorMessage={errors.name} label='Name' isRequired />
React Hook Form
It's taken from the official of react aria components documentation.
import { Controller, useForm } from "react-hook-form"
import { Button, FieldError, Form, Input, Label, TextField } from "react-aria-components"
function App() {
const { handleSubmit, control } = useForm({
defaultValues: {
name: ""
}
})
const onSubmit = (data) => {
// Do something with the form data
}
return (
<Form onSubmit={handleSubmit(onSubmit)}>
<Controller
control={control}
name="name"
rules={{ required: "Name is required." }}
render={({
field: { name, value, onChange, onBlur, ref },
fieldState: { invalid, error }
}) => (
<TextField
name={name}
value={value}
onChange={onChange}
onBlur={onBlur}
isInvalid={invalid}
validationBehavior="aria"
isRequired
>
<Label>Name</Label>
<Input ref={ref} />
<FieldError>{error?.message}</FieldError>
</TextField>
)}
/>
<Button type="submit">Submit</Button>
</Form>
)
}