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")} />
)}
Top comments (5)
Not working in react-router-dom v6
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...
That will work too, still need the render with the func inside.
Yeah, it worked :)
There's one too many "}" in your redirect definition