|
| 1 | +# Consumer Setup Guide |
| 2 | + |
| 3 | +This guide covers how to integrate `@lambdacurry/forms` with React Router v7 applications using remix-hook-form. |
| 4 | + |
| 5 | +## React Router v7 Vite Configuration |
| 6 | + |
| 7 | +When using `@lambdacurry/forms` with `remix-hook-form` in a React Router v7 application, you must configure Vite to bundle these packages together. Without this configuration, forms that render conditionally (e.g., triggered by a button click) will fail with: |
| 8 | + |
| 9 | +``` |
| 10 | +Error: useHref() may be used only in the context of a <Router> component. |
| 11 | +``` |
| 12 | + |
| 13 | +### Why This Happens |
| 14 | + |
| 15 | +`remix-hook-form`'s `useRemixForm` hook internally calls `useHref("/")`. When Vite's SSR bundling doesn't properly handle `remix-hook-form` and `react-hook-form`, these packages load with a separate instance of `react-router` that doesn't share the router context with your application. |
| 16 | + |
| 17 | +This causes `useHref()` to fail because the hook is looking for router context in the wrong React tree. |
| 18 | + |
| 19 | +### Required Vite Configuration |
| 20 | + |
| 21 | +Add these settings to your application's `vite.config.ts`: |
| 22 | + |
| 23 | +```typescript |
| 24 | +import { reactRouter } from '@react-router/dev/vite'; |
| 25 | +import tailwindcss from '@tailwindcss/vite'; |
| 26 | +import { defineConfig } from 'vite'; |
| 27 | +import tsconfigPaths from 'vite-tsconfig-paths'; |
| 28 | + |
| 29 | +export default defineConfig({ |
| 30 | + plugins: [reactRouter(), tsconfigPaths(), tailwindcss()], |
| 31 | + ssr: { |
| 32 | + // CRITICAL: Bundle these packages with the app to share react-router context |
| 33 | + noExternal: ['react-hook-form', 'remix-hook-form', '@lambdacurry/forms'] |
| 34 | + }, |
| 35 | + optimizeDeps: { |
| 36 | + // Pre-bundle dependencies to avoid runtime context issues |
| 37 | + include: ['react', 'react-dom', 'react-router', 'react-hook-form', 'remix-hook-form'], |
| 38 | + // Ensure single instances of these packages |
| 39 | + dedupe: ['react', 'react-dom', 'react-router', 'react-hook-form', 'remix-hook-form'] |
| 40 | + } |
| 41 | +}); |
| 42 | +``` |
| 43 | + |
| 44 | +### Configuration Breakdown |
| 45 | + |
| 46 | +| Setting | Purpose | |
| 47 | +|---------|---------| |
| 48 | +| `ssr.noExternal` | Forces Vite to bundle `remix-hook-form`, `react-hook-form`, and `@lambdacurry/forms` with the application instead of treating them as external dependencies. This ensures they share the same `react-router` instance. | |
| 49 | +| `optimizeDeps.include` | Pre-bundles these packages during dev, avoiding lazy loading that can cause context issues. | |
| 50 | +| `optimizeDeps.dedupe` | Ensures only one copy of each package exists, preventing multiple React or react-router instances. | |
| 51 | + |
| 52 | +## Recommended Form Pattern |
| 53 | + |
| 54 | +Here's the recommended pattern for using `@lambdacurry/forms` with `remix-hook-form`: |
| 55 | + |
| 56 | +```typescript |
| 57 | +import { zodResolver } from '@hookform/resolvers/zod'; |
| 58 | +import { FormError, HiddenField, Textarea } from '@lambdacurry/forms'; |
| 59 | +import { useEffect } from 'react'; |
| 60 | +import { useFetcher, useRevalidator } from 'react-router'; |
| 61 | +import { createFormData, RemixFormProvider, useRemixForm } from 'remix-hook-form'; |
| 62 | +import { z } from 'zod'; |
| 63 | + |
| 64 | +const schema = z.object({ |
| 65 | + text: z.string().min(1, 'Required'), |
| 66 | + author: z.string().default('User'), |
| 67 | +}); |
| 68 | + |
| 69 | +type FormData = z.infer<typeof schema>; |
| 70 | + |
| 71 | +function MyForm({ onSuccess }: { onSuccess: () => void }) { |
| 72 | + const fetcher = useFetcher<{ success?: boolean; errors?: Record<string, { message: string }> }>(); |
| 73 | + const revalidator = useRevalidator(); |
| 74 | + |
| 75 | + const methods = useRemixForm<FormData>({ |
| 76 | + resolver: zodResolver(schema), |
| 77 | + defaultValues: { text: '', author: 'User' }, |
| 78 | + fetcher, |
| 79 | + submitHandlers: { |
| 80 | + onValid: (data) => { |
| 81 | + // IMPORTANT: Use createFormData() to properly serialize |
| 82 | + fetcher.submit(createFormData(data), { |
| 83 | + method: 'post', |
| 84 | + action: '/api/endpoint', |
| 85 | + }); |
| 86 | + }, |
| 87 | + }, |
| 88 | + }); |
| 89 | + |
| 90 | + useEffect(() => { |
| 91 | + if (fetcher.state === 'idle' && fetcher.data?.success) { |
| 92 | + revalidator.revalidate(); |
| 93 | + methods.reset(); |
| 94 | + onSuccess(); |
| 95 | + } |
| 96 | + }, [fetcher.state, fetcher.data, revalidator, onSuccess, methods]); |
| 97 | + |
| 98 | + return ( |
| 99 | + <RemixFormProvider {...methods}> |
| 100 | + <form onSubmit={methods.handleSubmit}> |
| 101 | + <Textarea name="text" placeholder="Enter text..." rows={4} autoFocus /> |
| 102 | + <HiddenField name="author" /> |
| 103 | + <FormError className="mt-2" /> |
| 104 | + <button type="submit" disabled={fetcher.state !== 'idle'}> |
| 105 | + {fetcher.state !== 'idle' ? 'Submitting...' : 'Submit'} |
| 106 | + </button> |
| 107 | + </form> |
| 108 | + </RemixFormProvider> |
| 109 | + ); |
| 110 | +} |
| 111 | +``` |
| 112 | + |
| 113 | +### Key Points |
| 114 | + |
| 115 | +1. **Use `createFormData()`** - When using `submitHandlers.onValid`, always use `createFormData()` from `remix-hook-form` to properly serialize form data. |
| 116 | + |
| 117 | +2. **Use `useFetcher`** - For forms that don't navigate, use `useFetcher` instead of the standard form submission. |
| 118 | + |
| 119 | +3. **Handle revalidation** - Call `revalidator.revalidate()` after successful submission to refresh data. |
| 120 | + |
| 121 | +4. **Reset form state** - Call `methods.reset()` after successful submission to clear the form. |
| 122 | + |
| 123 | +## Troubleshooting |
| 124 | + |
| 125 | +### "useHref() may be used only in the context of a `<Router>` component" |
| 126 | + |
| 127 | +**Cause**: Vite is treating `remix-hook-form` or `react-hook-form` as external dependencies, causing them to load with a separate `react-router` instance. |
| 128 | + |
| 129 | +**Solution**: Add the `ssr.noExternal` and `optimizeDeps` configuration shown above. |
| 130 | + |
| 131 | +### Form works on initial render but fails when opened dynamically |
| 132 | + |
| 133 | +**Cause**: Same as above - the packages are being loaded lazily with a different router context. |
| 134 | + |
| 135 | +**Solution**: Ensure all three packages (`react-hook-form`, `remix-hook-form`, `@lambdacurry/forms`) are listed in `ssr.noExternal`. |
| 136 | + |
| 137 | +### Multiple React instances warning |
| 138 | + |
| 139 | +**Cause**: Dependencies are being duplicated in the bundle. |
| 140 | + |
| 141 | +**Solution**: Add `optimizeDeps.dedupe` with React and related packages. |
| 142 | + |
| 143 | +## Related Documentation |
| 144 | + |
| 145 | +- [Form Component Patterns](../packages/components/src/remix-hook-form/README.md) |
| 146 | +- [FormError Component Guide](./form-error-guide.md) |
| 147 | +- [remix-hook-form Documentation](https://github.com/Code-Forge-Net/remix-hook-form) |
0 commit comments