DEV Community

Malki Davis
Malki Davis

Posted on • Updated on

Redirecting to an external URL within React Router

TIL: How to redirect to an external URL within react-router-dom

At my current development position at Astrolabe Diagnostics
I was tasked with a route loading a React component if the user was signed in, or redirecting to an external site. I wanted to do this from the route level instead of handling the redirect from the component.

We simply need to render a function assigning the window.location to the new site, and the user is redirected.

{this.state.session.user ? (
  <Route exact path="/" component={MyComponent} />
  ) : (
  <Route exact path="/" render={() => (window.location = "https://redirectsite.com")} />
)}
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
avik6028 profile image
Avik Kundu

Not working in react-router-dom v6

Collapse
 
pvafc profile image
Prasanth Vaaheeswaran

Have you looked into the assign and replace methods on location? Wondering if those would also do the trick. developer.mozilla.org/en-US/docs/W...

Collapse
 
mxdavis profile image
Malki Davis

That will work too, still need the render with the func inside.

Collapse
 
ebrahimsani profile image
Ebrahim Sani

Yeah, it worked :)

Collapse
 
slashwhatever profile image
James

There's one too many "}" in your redirect definition