R
Reactiflux

kuba_huba – 17-21 Sep 2

kuba_huba – 17-21 Sep 2

KKuba9/2/2023
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? 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. 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.
I'm just missing why would the event on the button seem to "persist" after the element changes to a different one.
UUUnknown User9/4/2023
4 Messages Not Public
Sign In & Join Server To View

Looking for more? Join the community!

R
Reactiflux

kuba_huba – 17-21 Sep 2

Join Server