How to redirect to an external url in your React app

Pere Sola - Jul 21 '20 - - Dev Community

(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/

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .