FormField onClickevent called many times #8076
sunchuanstc
started this conversation in
General
Replies: 1 comment
-
The issue you're experiencing is likely due to event bubbling in the DOM, not a problem with React Hook Form itself.When you click on a nested div, the click event bubbles up through the DOM tree, triggering click handlers on parent elements as well. In your case: When you click the "bbb" div (with testEvent("2")), it triggers that handler, The event then bubbles up to the parent "aaa" div, triggering testEvent("1") as well and This results in both handlers being calledSolution: Stop Event PropagationModify your click handlers to prevent event bubbling: const testEvent = (value, event) => {
event.stopPropagation(); // Prevent event from bubbling up
a.setValue("ideImage", value);
}
// Update onClick handlers:
<div style={{ border: "1px red solid" }} onClick={(e) => testEvent("1", e)}>
aaa
<div style={{ border: "1px skyblue solid" }} onClick={(e) => testEvent("2", e)}>
bbb
<FormControl>
<RadioGroupItem value="2" />
</FormControl>
</div>
<div style={{ border: "1px black solid" }} onClick={(e) => testEvent("3", e)}>
ccc
<FormControl>
<RadioGroupItem value="3" />
</FormControl>
</div>
</div> Alternative approaches you could also use:
<div style={{ border: "1px red solid" }} onClick={(e) => testEvent("1", e)}>
aaa
</div>
<div style={{ border: "1px skyblue solid" }} onClick={(e) => testEvent("2", e)}>
bbb
</div>
<div style={{ border: "1px black solid" }} onClick={(e) => testEvent("3", e)}>
ccc
</div>
const testEvent = (value, event) => {
if (event.target === event.currentTarget) {
// Only execute if the click was directly on this element, not a child
a.setValue("ideImage", value);
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
const a = useForm({ mode: "all", resolver: zodResolver(createIDEFormSchema), defaultValues: { ideName: "aa", ideType: 1, ideImage: "2" } })
const testEvent = (value) =>{
a.setValue("ideImage",value);
}
//<Form {...a}>
<FormField
control={a.control}
name="ideImage"
render={({ field }) => (
...
<div style={{ border: "1px red solid" }} onClick={()=>{testEvent("1")}}>
aaa
//
Hi, when I click the div aaa /div,testEvent("1") will be called, and then testEvent("1") and testEvent("2") call twice, why? can anyone help me? it seems the react hook form has some problom
Beta Was this translation helpful? Give feedback.
All reactions