DEV Community

Pere Sola
Pere Sola

Posted on

21

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/

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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?

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay