DEV Community

Pere Sola
Pere Sola

Posted on

How to redirect to an external url in your React app

(it would be cool if Dev.to integrated with Unsplash.com so folks could add nice cover images..)

I am building a URL shortener for my own personal use. It's a fun little project that stretches your brain and skills quite a lot, loving it so far.

Today I was looking for ways to redirect to an external URL. My first instinct was to reach out for React-Router-DOM capabilities. I found this post [0] and I started to tinker with <Redirect to='path' /> [1].

It didn't work - I learnt that React-Router-DOM is for routing within the app. As folks in reddit were saying [2], you need to reach out to JS for that:

window.location.href = 'http://domain.com';
Enter fullscreen mode Exit fullscreen mode

It worked for me. Please leave a comment if there are better/more elegant ways to do it.

[0] https://dev.to/projectescape/programmatic-navigation-in-react-3p1l
[1] https://reactrouter.com/web/api/Redirect
[2] https://www.reddit.com/r/reactjs/comments/635dkv/redirect_outside_of_application_with_reactrouter/

Top comments (3)

Collapse
 
pradeepranasinghe profile image
pradeepranasinghe

Many thanks Pere Sola, I just signed up to say thank you for publishing your article. This saved my day! Good on you!

Collapse
 
petrussola profile image
Pere Sola

Glad it helped!

Collapse
 
ayuship1623 profile image
ayuship1623

window.location.href redirect to external URL using GET method. Is there any way to redirect using POST method?