H5W3
当前位置:H5W3 > 问答 > 正文

React-Router External link

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

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.

本文地址:H5W3 » React-Router External link

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址