DEV Community

Sébastien Belzile
Sébastien Belzile

Posted on • Updated on

Don't redirect in a callback

I have to correct this every time I join a new project: in a web application, do not redirect users in a callback. Use an anchor (a) tag instead.

Bad

function onClick() {
  [...].goto('/patate')
}
Enter fullscreen mode Exit fullscreen mode
<button onclick="onClick()">Potato page</button>
Enter fullscreen mode Exit fullscreen mode

Good

<a href="/patate">Potato page</a>
Enter fullscreen mode Exit fullscreen mode

Why is the handler bad?

  1. Requires JS to work.
  2. You are losing all the built-in browser functionalities. With a callback, one cannot:

    1. Right-click + Open in a new tab (and the other right click options)
    2. See whether he has already visited a link (although most people get rid of that visual feedback)

When to stop using an anchor?

If you need to run JS for purposes other than user redirection. Ex:

  • Calling an API then redirecting
  • Running validations then redirecting
  • etc.

In those cases, you may use a callback.

Top comments (0)