React-Router External link React-Router External link javascript javascript

React-Router External link


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.


With Link component of react-router you can do that. In the "to" prop you can specify 3 types of data:

  • a string: A string representation of the Link location, created by concatenating the location’s pathname, search, and hash properties.
  • an object: An object that can have any of the following properties:
    • pathname: A string representing the path to link to.
    • search: A string representation of query parameters.
    • hash: A hash to put in the URL, e.g. #a-hash.
    • state: State to persist to the location.
  • a function: A function to which current location is passed as an argument and which should return location representation as a string or as an object

For your example (external link):

https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies

You can do the following:

<Link to={{ pathname: "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies" }} target="_blank" />

You can also pass props you’d like to be on the such as a title, id, className, etc.


There is no need to use <Link /> component from react-router.

If you want to go to external link use an anchor tag.

<a target="_blank" href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>