React-Router External link

Eric Hodonsky picture Eric Hodonsky · Mar 20, 2017 · Viewed 202.7k times · Source

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"
}

Answer

Evgeny Lukianchikov picture Evgeny Lukianchikov · Jun 15, 2017

Here's a one-liner for using React Router to redirect to an external link:

<Route path='/privacy-policy' component={() => { 
     window.location.href = 'https://example.com/1234'; 
     return null;
}}/>

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.