How to access form context created in a library from app #12576
-
I've created a library package that uses react-hook-form and exports an array of components amongst which a wrapper that uses The problem is that when I try to directly use // src/app/page.js
import { MyForm, MyFormInput } from 'my-custom-form'
import CustomInput from '@/components/custom-input'
export default function Page() {
return (
<MyForm>
<MyFormInput /> // This component is provided by the library and works fine
<CustomInput /> // This component is provided by the app and doesn't work
</MyForm>
)
} // src/components/custom-input.js (Next.ts App)
'use client'
import { useFormContext } from 'react-hook-form'
export default function CustomInput() {
const { register } = useFormContext(); // ERROR: Cannot read properties of null (reading 'register')
return <input {...register('name')} />
} // node_modules/my-custom-form/dist/index.js (My Package)
'use client'
import { useForm, FormProvider } from 'react-hook-form'
export default function MyForm({ children }) {
const methods = useForm();
return (
<FormProvider {...methods}>
<form>
{children}
</form>
</FormProvider>
)
} Details
Similiar topics#3894 discusses a similar issue, but as I read it, they are having problems with inputs provided by the library not being able to use |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Can you post a CodeSandbox that reproduces your problem? |
Beta Was this translation helpful? Give feedback.
-
We'll after hours of searching without result. I tried something which managed to work. I just exported a custom hook from the package to use in my app and it seems to be working... bitter sweet. // node_modules/my-custom-form/dist/my-form-context.js (My Package)
import { useFormContext } from 'react-hook-form';
export const useMyFormContext = useFormContext(); |
Beta Was this translation helpful? Give feedback.
-
@douwepausma Per the RHF documentation, you should be wrapping the form itself in a FormProvider. That is what makes the context available to useFormContext calls in the components themselves. This works fine for all my forms that have components that rely on useFormContext() internally. Why does it work for the library-provided component? Probably because the component itself is doing something similar. |
Beta Was this translation helpful? Give feedback.
We'll after hours of searching without result. I tried something which managed to work. I just exported a custom hook from the package to use in my app and it seems to be working... bitter sweet.