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 = "")} />
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

avik6028 profile image
Avik Kundu

Not working in react-router-dom v6

pvafc profile image
Prasanth Vaaheeswaran

Have you looked into the assign and replace methods on location? Wondering if those would also do the trick.

mxdavis profile image
Malki Davis

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

ebrahimsani profile image
Ebrahim Sani

Yeah, it worked :)

slashwhatever profile image

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