3rd Practical Class:
Forms in React
🎯 Learning Objectives
By the end of this session, you will be able to:
- Understand the different approaches to handling forms in React
- Build accessible forms using Chakra UI components
- Implement form validation with React Hook Form and Zod
- Create reusable form field components
🤔 The Problem: Why Do We Need Form Libraries?
What happens when you build forms with just React?
Problems with this approach:
- ❌ Lots of manual code to write
- ❌ Manual validation logic
- ❌ No advanced accessibility and UX features
- ❌ Poor performance (re-renders on every keystroke)
🏗️ Building Blocks: Chakra UI Form Components
Step 1: Understanding Field Components
Chakra UI provides accessible form components that automatically handle:
- Automatic ID management: Labels and inputs are automatically connected
- Screen reader support: Proper ARIA attributes and semantic structure
- Validation states: Automatic styling for error, success, and focus states
- Cross-browser consistency: Uniform appearance across all browsers
- Built-in accessibility: No manual work needed for WCAG compliance
*Key Components:
- : Wrapper that provides context and accessibility
- : Automatically connects to input with and
- : Shows validation errors
- : Provides additional context
⚡ React Hook Form
Why React Hook Form?
- ✅ Performance: Minimal re-renders
- ✅ Accessibility: Built-in support
- ✅ Validation: Schema-based validation
- ✅ Type Safety: Full TypeScript support
- ✅ Developer Experience: Less boilerplate
Step 2: Basic React Hook Form Setup
🔒 Schema Validation with Zod
Why Schema Validation?
Instead of inline validation rules, we can define schemas that are:
- ✅ Type-safe with TypeScript
- ✅ Self-documenting code
- ✅ Readable defined outside of the component
- ✅ Testable validation logic
Step 3: Zod Schema Definition
🧩 Bonus: Building Reusable Components
🎯 Final Exercise: Build a Complete Form
- Fields: First Name, Last Name, Email, Message
- Validation:
- All fields are required
- Email must be valid
- Message must be at least 10 characters
- React Hook Form for form state management
- Zod for schema validation