[Smart Form] How to Watch Specific Form Fields from Parent Component in React Hook Form? #12410
Replies: 3 comments 6 replies
-
@bluebill1049 Could you please give me some ideas? Thanks |
Beta Was this translation helpful? Give feedback.
-
There are two variants of const FIELDS_TO_WATCH = ["name"];
const { unsubscribe } = formRef.current.watch((values: IFormValues, { name, type }: { name: string, type: EventType }) => {
if (!FIELDS_TO_WATCH.includes(name) || !type) return;
console.log('Form values changed:', values);
}); This will work, but I'm confused about why you are trying to watch values in the parent component even though the form is defined in the child. That seems like a lot of extra boilerplate and complexity for no gain. In particular, all of the complexity with function Parent() {
function watchCallback(name: string) {
}
return (
<Child watchCallback={watchCallback} />
);
}
const FIELDS_TO_WATCH = ["name"];
function Child({ watchCallback }: { watchCallback?: (name: string) => void }) {
const form = useForm();
const { watch } = form;
useEffect(() => {
const subscription = watch((_value, { name, type }) => {
if (!FIELDS_TO_WATCH.includes(name) || !type) return;
watchCallback.?(name);
});
return () => subscription.unsubscribe();
}, [watch]);
return (
<form>
</form>
)
} |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I’m currently working with a form component using react-hook-form wrapped inside a SmartForm component. My goal is to be able to watch specific form fields (like name, address, etc.) in the parent component.
Right now, I have a setup where I can watch all form values at once, but I want to limit it to just certain fields from the parent. Is there a clean way to do this? Specifically, I want to pass watch to the parent component and track individual fields as they change.
Here’s what I have so far:
CodeSanbox Link
What I Need Help With:
Beta Was this translation helpful? Give feedback.
All reactions