8
Components

Form

A powerful and flexible form component with React Hook Form integration, advanced validations, and dynamic fields.

Form Component

Forms are essential in modern web applications. The Form component streamlines form creation with React Hook Form, ensuring accessible, validated, and visually consistent forms. Built with best practices in mind, it offers:

  • Semantic structure and accessibility
  • Support for schema-based validation using zod
  • Integration with React Hook Form
  • Fully customizable styling and markup
  • Server Actions support for Next.js applications
Create Account
Password requirements:
  • 8+ characters
  • Uppercase letter
  • Lowercase letter
  • Number
  • Special character

Installation

Install the form component using the following command:

npx axionjs-ui add form

This will add the Form component and its dependencies to your project.

File Structure

form.tsx
label.tsx
input.tsx

Component API

PropTypeDefault
Form
React.ComponentType<FormProviderProps>
-
FormField
React.ComponentType<ControllerProps>
-
FormItem
React.ForwardRefExoticComponent<React.HTMLAttributes<HTMLDivElement>>
-
FormLabel
React.ForwardRefExoticComponent<React.ComponentPropsWithoutRef<typeof Label>>
-
FormControl
React.ForwardRefExoticComponent<React.ComponentPropsWithoutRef<typeof Slot>>
-
FormDescription
React.ForwardRefExoticComponent<React.HTMLAttributes<HTMLParagraphElement>>
-
FormMessage
React.ForwardRefExoticComponent<React.HTMLAttributes<HTMLParagraphElement>>
-
useFormField
() => { id: string; name: string; formItemId: string; formDescriptionId: string; formMessageId: string; error: FieldError | undefined }
-

Basic Usage Examples

Login Form

Login

Registration Form with Password Validation

Create Account
Password requirements:
  • 8+ characters
  • Uppercase letter
  • Lowercase letter
  • Number
  • Special character

Tag Input Form

Interest Tags

Add up to 5 tags representing your interests.

0/5 tags

Advanced Usage Examples

Multi-step Form with Local Storage

Multi-step Form with Progress Saving
Complete your profile in three simple steps
1
Personal
2
Address
3
Preferences
Your progress is automatically saved

Server Action Form

Contact Us
Send us a message and we'll get back to you as soon as possible.

Form Validation

The Form component is designed to work seamlessly with Zod for validation. Here’s how to set up validation for your forms:

Basic Validation

const formSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters."),
  email: z.string().email("Please enter a valid email address."),
  age: z.number().min(18, "You must be at least 18 years old."),
});

Conditional Validation

const formSchema = z.object({
  employmentStatus: z.enum(["employed", "unemployed", "student"]),
  companyName: z.string().optional(),
}).refine((data) => {
  // If employed, company name is required
  if (data.employmentStatus === "employed" && !data.companyName) {
    return false;
  }
  return true;
}, {
  message: "Company name is required for employed individuals.",
  path: ["companyName"],
});

Custom Validation

const formSchema = z.object({
  username: z.string()
    .min(3, "Username must be at least 3 characters")
    .refine(async (username) => {
      // Check if username is available (example)
      const response = await fetch(`/api/check-username?username=${username}`);
      const data = await response.json();
      return data.available;
    }, "This username is already taken"),
});

Accessibility

The Form component is built with accessibility in mind, following best practices to ensure your forms are usable by everyone, including those using assistive technologies.

  • ARIA Attributes: Automatically adds relevant ARIA attributes to form elements, including aria-invalid and aria-describedby for form controls with errors
  • Form Labels: Proper label association with form controls using htmlFor and id attributes
  • Error Announcements: Error messages are properly associated with their corresponding form controls for screen readers
  • Keyboard Navigation: All form controls are keyboard accessible and follow a logical tab order
  • Focus Management: Preserves focus management for dynamic forms and multi-step forms

Best Practices

Form Organization

  • Group related form fields together using fieldsets or sections
  • Use clear and concise labels for form fields
  • Provide guidance using FormDescription for complex fields
  • Place error messages directly below the form field they relate to

Validation

  • Validate forms on both client and server
  • Provide clear and helpful error messages
  • Use appropriate validation triggers (onChange, onBlur, onSubmit)
  • Consider using client-side validation for immediate feedback and server validation for security

Performance

  • For large forms, consider splitting them into multiple steps
  • Use React Hook Form’s efficient re-rendering to minimize performance impact
  • For very complex forms, consider controlled components only for fields that need it

Server Integration

  • For Next.js applications, use Server Actions for form processing
  • Consider using the useTransition hook for better loading states
  • Implement client-side validation before submitting to the server

Customization

The Form component is designed to be customizable to match your application’s design system. Here are some common customization points:

Styling

<FormItem className="custom-form-item-class">
  <FormLabel className="custom-label-class">Name</FormLabel>
  <FormControl className="custom-control-wrapper">
    <Input className="custom-input-class" />
  </FormControl>
  <FormDescription className="custom-description-class">
    Enter your full name.
  </FormDescription>
  <FormMessage className="custom-message-class" />
</FormItem>

Custom Form Controls

<FormField
  name="rating"
  control={form.control}
  render={({ field }) => (
    <FormItem>
      <FormLabel>Rating</FormLabel>
      <FormControl>
        <CustomStarRating
          value={field.value}
          onChange={field.onChange}
        />
      </FormControl>
      <FormMessage />
    </FormItem>
  )}
/>

Conclusion

The Form component provides a powerful and flexible foundation for building forms in your React applications. With its integration with React Hook Form and Zod, it offers a complete solution for form state management and validation, while maintaining full accessibility and customization options.

By combining the Form component with other UI components like Input, Select, Checkbox, and more, you can build complex forms that provide a great user experience while maintaining code quality and type safety.

Whether you’re building a simple login form or a complex multi-step wizard, the Form component provides the building blocks you need to create accessible, validated, and user-friendly forms.