Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

determine event order in React onEvent properties

Imagine an HTML element like the following:

<a onClick={() => console.log("side effect that needs to fire before the redirect"} href="yourlink.com">Click me</a>

Here the event onClick gets executed before the user is redirected. Is this always the case or is this undefined or does this depend on the browser?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Is this always the case…

Yes, the default action of an event (such as following a link), if any, is not triggered until the event handlers have been called, not least because the event handlers could prevent it from happening by calling preventDefault on the event object.

Beware, though, that when the page is being left, (almost) any outstanding asynchronous work will be terminated. So your event handler can’t (for instance) send a standard ajax request to the server; when the handler returns, that work is still in progress, and will be terminated when the page is torn down. (One exception to that is a beacon.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading