I want to use <a>
with both an href
and onClick
such that my code fully executes the passed onClick
handler before redirecting to the href
value:
Example:
const Link = ({ children, ...props }) => <a {...props}>{children}</a>;
const someTask = () => {
for (let i = 0; i < 1000; i++) {
console.log(i);
}
};
export default App = () => (
<Link href="https://stackoverflow.com" onClick={someTask}>
Click me
</Link>
);
Currently, the above will not log all numbers up to 1000 before redirecting. For me, ~180 numbers are logged before the redirect occurs.
I do not want a solution that sets href="#"
and handles the redirect inside the onClick
. This is because of accessibility reasons where my <a>
needs to have a clear href
attribute value.
Some similar posts I've looked into:
- How to execute onclick before navigating to a different page?
Suggests handling everything inside the
onClick
and not having anhref
- HTML tag <a> want to add both href and onclick working
Suggests having the
onClick
handler return true or false whether to allow thehref
, but React doesn't allow this syntax https://reactjs.org/docs/handling-events.html
I am open to other approaches as long as the generated <a>
has an honest href
and executes its onClick
handler fully.