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"
}
To expand on Alan's answer, you can create a
<Route/>
that redirects all<Link/>
's with "to" attributes containing 'http:' or 'https:' to the correct external resource.Below is a working example of this which can be placed directly into your
<Router>
.If you are using server side rending, you can use
StaticRouter
. With yourcontext
asprops
and then adding<Redirect path="/somewhere" />
component in your app. The idea is everytime react-router matches a redirect component it will add something into the context you passed into the static router to let you know your path matches a redirect component. now that you know you hit a redirect you just need to check if thats the redirect you are looking for. then just redirect through the server.ctx.redirect('https://example/com')
.It doesn't need to request react router. This action can be done natively and it is provided by the browser.
just use
window.location
There is no need to use
<Link />
component from react-router.If you want to go to external link use an anchor tag.
I actually ended up building my own Component.
<Redirect>
It takes info from thereact-router
element so I can keep it in my routes. Such as:Here is my component incase-anyone is curious:
EDIT -- NOTE: This is with
react-router: 3.0.5
, it is not so simple in 4.xI don't think React-Router provides this support. The documentation mentions
You could try using something like React-Redirect instead