# React Hook Form + Zod

> Controller binds the switch to RHF; Zod requires opt-in on submit.

A shadcn/ui block from the [@flx](https://ui.flexnative.com) registry, listed on [shadcn.exchange](https://shadcn.exchange/r/flx/switch-12).

- Page, with a live preview: https://shadcn.exchange/r/flx/switch-12
- Screenshot: https://abzjhwgwpdpz7ua5.public.blob.vercel-storage.com/shots/flx/switch-12-light-0381b31b8c337331.png
- Registry item: https://ui.flexnative.com/r/switch-12.json
- Listed: 2026-10-13, source last changed 2026-10-13

## Install

```bash
npx shadcn@latest add https://ui.flexnative.com/r/switch-12.json
```

Run it in a project that has shadcn/ui set up. It adds the files below and installs what they depend on.

## Dependencies

- npm packages: `@hookform/resolvers`, `react-hook-form`, `sonner`, `zod`
- Registry items: `switch`, `field`, `button`

## Files

### `registry/patterns/switch/switch-12.tsx`

```tsx
'use client'

import { zodResolver } from '@hookform/resolvers/zod'
import { Controller, useForm } from 'react-hook-form'
import { toast } from 'sonner'
import * as z from 'zod'

import { Button } from '@/components/ui/button'
import {
  Field,
  FieldContent,
  FieldDescription,
  FieldError,
  FieldLabel,
} from '@/components/ui/field'
import { Switch } from '@/components/ui/switch'

const formSchema = z.object({
  marketing: z.boolean().refine((value) => value === true, {
    message: 'You must opt in to receive updates.',
  }),
})

type FormValues = z.infer<typeof formSchema>

export function Switch12() {
  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      marketing: false,
    },
  })

  function onSubmit(data: FormValues) {
    toast.success('Submitted', { description: `marketing: ${data.marketing}` })
  }

  return (
    <form
      onSubmit={form.handleSubmit(onSubmit)}
      className="flex w-full max-w-sm flex-col gap-4"
    >
      <Controller
        name="marketing"
        control={form.control}
        render={({ field, fieldState }) => (
          <Field orientation="horizontal" data-invalid={fieldState.invalid}>
            <FieldContent>
              <FieldLabel htmlFor="switch-12">Marketing emails</FieldLabel>
              <FieldDescription>
                Receive product news and offers.
              </FieldDescription>
              {fieldState.invalid && (
                <FieldError errors={[fieldState.error]} />
              )}
            </FieldContent>
            <Switch
              id="switch-12"
              aria-invalid={fieldState.invalid}
              checked={field.value}
              onCheckedChange={field.onChange}
            />
          </Field>
        )}
      />
      <Button type="submit" size="sm" className="self-start">
        Submit
      </Button>
    </form>
  )
}
```
