0

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:

I am open to other approaches as long as the generated <a> has an honest href and executes its onClick handler fully.

Edwarric
  • 513
  • 2
  • 9
  • 19
  • what about using `preventDefault` and `stopImmediatePropagation`, and at the end of the task doing something like `window.location.href = event.target.href`? – Alberto Sinigaglia Jul 08 '21 at 00:41
  • @AlbertoSinigaglia I Tried setting `e.preventDefault(); e.nativeEvent.stopImmediatePropagation()` at the start of the task, and then `window.location.href = e.target.href` at the end. It still logs only around ~200 numbers before redirecting – Edwarric Jul 08 '21 at 00:54
  • You shouldn't focus on console.log not finishing its job. Console.log is slow and probably asynchronous, i.e. it doesn't wait for the text being effectively written before returning, so to stay apparently fast. If you can't return true or false in your onclick handler, then preventDefault should work, given that you don't run anything asynchronous in your onclick handler. – QuentinC Jul 08 '21 at 15:19

0 Answers0