Kuba
Kuba14mo ago

kuba_huba – 17-21 Sep 2

I was building a form today and I stumbled upon weird behavior. When I swapped buttons that were conditionally rendered, the event was firing when submit button was rendered.
<div className="mb-4">
<div className="flex gap-2">
<Button
className="w-2/3"
variant="outline"
onClick={handleNavigationBackward}
disabled={pagination.isFirstPage}
>
<IoArrowBack className="mr-2" /> Poprzednie
</Button>
{!pagination.isLastPage ? (
<Button
className="w-2/3"
type="button"
variant="outline"
key="navigation_button"
onClick={handleNavigationForward}
>
Next
<IoArrowForward className="ml-2" />
</Button>
) : (
<Button className="w-2/3" type="submit" key="submit_button">
Submit <IoPaperPlane className="ml-2" />
</Button>
)}
</div>
</div>
<div className="mb-4">
<div className="flex gap-2">
<Button
className="w-2/3"
variant="outline"
onClick={handleNavigationBackward}
disabled={pagination.isFirstPage}
>
<IoArrowBack className="mr-2" /> Poprzednie
</Button>
{!pagination.isLastPage ? (
<Button
className="w-2/3"
type="button"
variant="outline"
key="navigation_button"
onClick={handleNavigationForward}
>
Next
<IoArrowForward className="ml-2" />
</Button>
) : (
<Button className="w-2/3" type="submit" key="submit_button">
Submit <IoPaperPlane className="ml-2" />
</Button>
)}
</div>
</div>
Can anyone help me understand why adding a key was a valid solution?
5 Replies
Kuba
Kuba14mo ago
By weird behavior I mean that when the pagination.isLastPage changed and buttons also changed the submit event was fired instantly, despite button with type="submit" not being pressed.
Kuba
Kuba14mo ago
This SO question (https://stackoverflow.com/a/74083342/7585847) helped me, but as explained:
This could also be the React virtual DOM not realizing it is a different button while the event is propagating through, and passing the reference that was to the "edit" button to the new "send" button and rendering it in place while the effect of the button click on edit button still propagating, therefore effectively, submitting when it hits the form.
Stack Overflow
Render a button[type="submit"] in a form trigger the onSubmit callback
With a edit boolean state, I conditionally render a button of type "submit" inside a form element. However as you can see when I set edit to true and render the button, the onSubmit callb...
Kuba
Kuba14mo ago
I'm just missing why would the event on the button seem to "persist" after the element changes to a different one.
Unknown User
Unknown User14mo ago
Message Not Public
Sign In & Join Server To View
reactibot
reactibot14mo ago
This thread hasn’t had any activity in 36 hours, so it’s now locked. Threads are closed automatically after 36 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/902647189120118794/1147581978787463223