I am thinking of using this library for my next project. #1102
Replies: 2 comments
-
It's possible. You can use context. |
Beta Was this translation helpful? Give feedback.
-
Hi @heecheon92, Like epenflow has mentioned you can place the useForm hook inside a context, and providing you pass along the generics and return the useForm hook you can use it like normal anywhere inside of the context provider without prop drilling. Tanstack form is supposed to "headless", so in a sense they provide us with the fundamental building block (useForm) and we can use it how we like. It should looks something like this I guess. (may or may not work, just as an example... I'm at work, so this will will have to do for now) import React, { createContext, useContext, ReactNode } from 'react';
import { FormOptions, useForm, Validator } from '@tanstack/react-form';
interface FormContextType<TFormData, TFormValidator> {
form: ReturnType<typeof useForm<TFormData, TFormValidator>>;
}
const FormContext = createContext<FormContextType<any, any> | undefined>(undefined);
interface FormProviderProps<TFormData, TFormValidator> {
children: ReactNode;
options: FormOptions<TFormData, TFormValidator>;
}
export function FormProvider<TFormData, TFormValidator extends Validator<TFormData, unknown> | undefined = undefined>({
children,
options,
}: FormProviderProps<TFormData, TFormValidator>) {
const form = useForm<TFormData, TFormValidator>(options);
return <FormContext.Provider value={{ form }}>{children}</FormContext.Provider>;
}
export function useFormContext<TFormData, TFormValidator extends Validator<TFormData, unknown> | undefined = undefined>() {
const context = useContext(FormContext);
if (!context) {
throw new Error('useFormContext must be used within a FormProvider');
}
return context.form as ReturnType<typeof useForm<TFormData, TFormValidator>>;
} Be aware that since this exists in a context unless the context is "torn down" or "reset" it will persist, unlike a component based form, so you'll need to account for things like resetting it. See also #825 as it's kind of adjacent to what you want to do. |
Beta Was this translation helpful? Give feedback.
-
I can tell this library is built really well.
One question though, is it possible to pass around form state to "remote" component without prop drilling?
For example,
Beta Was this translation helpful? Give feedback.
All reactions