DEV Community

Ebraim Carvalho
Ebraim Carvalho

Posted on

A simple way to redirect react-router-dom

Well, I was researching how to redirect to another page / component by clicking on a simple button or returning a function and found this simple and easy way:

import { useHistory } from 'react-router-dom';

function app() {
  let history = useHistory();

  const redirect = () => {
    history.push('/your-path')
  }

  return (
    <div>
      <button onClick={redirect}>Redirect</button>
    </div>
  )
}

That simple!
I was struggling for a while because most of the examples were about reaction class components and I thought it prudent to leave that way to those who use react function components.

What other ways do you use to redirect?

Top comments (8)

Collapse
 
rohanfaiyazkhan profile image
Rohan Faiyaz Khan

This is not a good practice. You should use an <a /> tag or react-router-dom's <Link /> to handle your redirect. Even if you must redirect programatically, it is better to use a link and use event.preventDefault() on the click and only then use history.push().

There are two reasons why you should do this. Firstly accessibility. Screen readers won't know that your button can redirect. Anchor tags however get properly announced to users using assistive technology. The second reason is web crawlers won't follow your links and you will not get potential SEO benefits from it.

Collapse
 
ebraimcarvalho profile image
Ebraim Carvalho

Thanks for the comment, I forgot to mention that i needed to redirect after logout to Firebase, this snippet code shows more clearly

const logout = () => {
    firebase.logout()
      .then(result => {
        localStorage.removeItem('email')
        history.push('/login')
      })
      .catch(error => console.log('Error: ', error))
  }

In this case, do you recommend other approach?

Collapse
 
ajay_vasudev profile image
Ajay Vasudev

what u say is right. not denying it...but i also think the simple way would come in handy in some cases too. and most practically would be the best option.

Collapse
 
atharvakadlag profile image
Atharva Kadlag

thanks : )

Collapse
 
itsjzt profile image
Saurabh Sharma • Edited

You can always use the <Redirect /> component

dev.to/projectescape/programmatic-...

Collapse
 
zelal profile image
Zelal Hossain

Thanks for share

Collapse
 
giri14mct profile image
Giritharan

Thank you very very much dev... Because I struggle with many concepts finally it's help me lot.. I don't even have account in dev community, I want to tell my thanks to you that's why create my account...

Collapse
 
quoctrung163 profile image
Quốc Trung

Thank you