Since I'm using react-router to handle my routes in a react app, I'm curious if there is a way to redirect to an external resource.
Say someone hits:
example.com/privacy-policy
I would like it to redirect to:
example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
I'm finding exactly zero help in avoiding writing it in plain JS at my index.html loading with something like:
if ( window.location.path === "privacy-policy" ){
window.location = "example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
}
Using some of the info here, I came up with the following component which you can use within your route declarations. It's compatible with React Router v4.
It's using typescript, but should be fairly straight-forward to convert to native javascript:
And use with:
Here's a one-liner for using React Router to redirect to an external link:
It uses React pure component concept to reduce the component's code to a single function that, instead of rendering anything, redirects browser to an external URL.
Works both on React Router 3 and 4.
FOR V3, although it may work for V4. Going off of Relic's answer, I needed to do a little more, like handle local development where 'http' is not present on the url. I'm also redirecting to another application on the same server.
Added to router file:
And the Component:
Using React with Typescript you get an error as the function must return a react element, not
void
. So I did it this way using the Route render method (and using React router v4):Where you could instead also use
window.location.assign()
,window.location.replace()
etcI had luck with this:
I was able to achieve a redirect in react-router-dom using the following
For my case, I was looking for a way to redirect users whenever they visit the root URL
http://myapp.com
to somewhere else within the apphttp://myapp.com/newplace
. so the above helped.