158

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"
}
Eric Hodonsky
  • 4,117
  • 3
  • 22
  • 36
  • Which React Router are you using? – Tyler McGinnis Mar 20 '17 at 21:55
  • I'm using version 3.x – Eric Hodonsky May 16 '17 at 00:10
  • 1
    Simply change `window.location.href` to have a formal redirection. – Amirhossein Mehrvarzi Mar 02 '19 at 19:02
  • 3
    @AmirhosseinMehrvarzi that doesn't actually mean anything. Could you be more specific or give an example? Also I'm not sure if you've noticed but this question already has an accepted answer dealing with React & React Router which is what the question was about. – Eric Hodonsky Mar 04 '19 at 15:59
  • 1
    @Relic You need to use that as your url in your if condition. I had similar problem a few days ago and found this way simple and effective. It redirects immediately. **Accepted answer** is a *Routing solution* (While it violates Route principles, considering that Route architecture is for **navigation inside the App** not for outside) which doesn't work for any environment like mine – Amirhossein Mehrvarzi Mar 04 '19 at 19:06
  • @AmirhosseinMehrvarzi the redirect is instant regardless... – Eric Hodonsky Mar 05 '19 at 20:08
  • @AmirhosseinMehrvarzi This question is very specific and the solution here speaks too it. It was looking for something that broke them because there was no 'redirect' built into this router which IS part of routing principals. Consider 301 & 302. The accepted answer is exactly a redirect. Which, because it can't carry the response headers is not a great idea but when you have a SPA with no domain hits from URIs there no way to do it from the server / cloudfront. This is the only solution within React for the OP. – Eric Hodonsky Mar 05 '19 at 20:11
  • Also @AmirhosseinMehrvarzi if you're not using the react environment this question isn't for you, nor is the answer. So it makes sense it doesn't work. – Eric Hodonsky Mar 05 '19 at 20:12
  • @Relic No :-). I had a React project. The meaning of environment is using `js` or `ts`, `es2015` or .... They affect the solution. I used my solution and is working properly. To continue conversation please go to chatroom. Here is forbidden. Thanks. – Amirhossein Mehrvarzi Mar 05 '19 at 20:25
  • @AmirhosseinMehrvarzi those things were irrelevant... and I'm glad you found your own solution. If you notice I found my own solution too :D – Eric Hodonsky Mar 06 '19 at 21:08
  • window.location.href may cause cross scripting issue right ? is there a way to work around that ? – user2128 Feb 03 '21 at 02:55

17 Answers17

212

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.

mawburn
  • 2,048
  • 4
  • 27
  • 46
Evgeny Lukianchikov
  • 2,875
  • 3
  • 13
  • 9
  • 2
    This works but I was looking for a more elegant scalable solution. See what I came up with as it allowed me to go even further with redirects for MobileApps etc ( Not ReactNative, truly Native apps ). Now what I'm doing isn't the right way to solve my problem, but to solve this problem I suggest you investigate my solution as well if for nothing else than a different perspective. – Eric Hodonsky Jun 16 '17 at 19:13
  • 1
    This is not really that clean in my mind. I would rather use an anchor tag honestly. Second, hitting the back button on the browser returns you the route that then redirects back to https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies – Jonathan Rys Sep 06 '17 at 19:12
  • 17
    For better back button behavior (verify for your application), use window.location.replace('http://example.com') – MattC Jul 17 '18 at 13:53
  • 1
    None of the answers do, the original post was asking about client redirects only, WHILE being aware that there is no 301 or 302 type true redirect support. – Eric Hodonsky Apr 07 '19 at 19:16
  • 1
    `window.location.href` is not optimal. If the user clicks the browser 'back' button after being redirected, she will get to the route that will immediately redirect her again. To avoid this, better use `window.location.replace()`. Source: https://stackoverflow.com/a/506004/163411 – targumon Dec 17 '20 at 14:51
71

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>
Diego Laciar
  • 1,496
  • 1
  • 12
  • 7
67

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.

Víctor Daniel
  • 899
  • 8
  • 6
48

I actually ended up building my own Component. <Redirect> It takes info from the react-router element so I can keep it in my routes. Such as:

<Route
  path="/privacy-policy"
  component={ Redirect }
  loc="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies"
  />

Here is my component incase-anyone is curious:

import React, { Component } from "react";

export class Redirect extends Component {
  constructor( props ){
    super();
    this.state = { ...props };
  }
  componentWillMount(){
    window.location = this.state.route.loc;
  }
  render(){
    return (<section>Redirecting...</section>);
  }
}

export default Redirect;

EDIT -- NOTE: This is with react-router: 3.0.5, it is not so simple in 4.x

Eric Hodonsky
  • 4,117
  • 3
  • 22
  • 36
  • you don't HAVE to do anything, react is a framework, and there is a lot of value in a framework. THIS is how to do it within the react framework. It DOES NOT however take into account the browser history module that could be wrapped in here to, making this even more useful. Also Please note "window.location" is how it was done in 1999. This is just a way to add it to your routes table for client side routing. It's not a "good" solution. – Eric Hodonsky Jul 03 '17 at 17:37
  • in react -router v4 you can use render instead component – Irrech Feb 22 '18 at 13:39
  • 4
    @Irrech "render instead component" means nothing. If you have an answer to the question please add it and give some detail of how you would implement. – Eric Hodonsky Feb 27 '18 at 17:16
  • 5
    @MuhammadUmer or you just use an anchor tag. react-router is pretty strictly meant for routing just within your application. you can disagree with that design decision (i know *i* do), but it's not "done better in 1999", it's just done the same. – worc Oct 02 '18 at 18:10
  • What if we want to pass the URL also dynamically along with HTTP Status code while redirecting to external site. I got some example, but its not clear with my requirement https://gist.github.com/arasmussen/f2c01dc858481590f6bffae6b540632c – Krishna Mani Sep 09 '20 at 15:11
42

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

class RedirectPage extends React.Component {
  componentDidMount(){
    window.location.replace('https://www.google.com')
  }
}

also, if you want to open it in a new tab:

window.open('https://www.google.com', '_blank');
Alan
  • 4,576
  • 25
  • 43
  • 1
    This answer is incomplete, doesn't allow for abstraction or it's relation to the router – Eric Hodonsky Dec 03 '18 at 21:30
  • 15
    This is the goal. It doesn't need to request react router. This action can be done natively and it is provided by the browser. – Alan Dec 04 '18 at 23:56
  • What if we want to pass the URL also dynamically along with HTTP Status code while redirecting to external site. I got some example, but its not clear with my requirement. https://gist.github.com/arasmussen/f2c01dc858481590f6bffae6b540632c – Krishna Mani Sep 09 '20 at 15:11
7

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:

interface Props {
  exact?: boolean;
  link: string;
  path: string;
  sensitive?: boolean;
  strict?: boolean;
}

const ExternalRedirect: React.FC<Props> = (props: Props) => {
  const { link, ...routeProps } = props;

  return (
    <Route
      {...routeProps}
      render={() => {
        window.location.replace(props.link);
        return null;
      }}
    />
  );
};

And use with:

<ExternalRedirect
  exact={true}
  path={'/privacy-policy'}
  link={'https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies'}
/>
Jens Bodal
  • 1,347
  • 1
  • 16
  • 30
4

I had luck with this:

  <Route
    path="/example"
    component={() => {
    global.window && (global.window.location.href = 'https://example.com');
    return null;
    }}
/>
Ajith
  • 990
  • 2
  • 7
  • 26
2

I don't think React-Router provides this support. The documentation mentions

A < Redirect > sets up a redirect to another route in your application to maintain old URLs.

You could try using something like React-Redirect instead

ytibrewala
  • 461
  • 1
  • 4
  • 11
1

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>.

<Route path={['/http:', '/https:']} component={props => {
  window.location.replace(props.location.pathname.substr(1)) // substr(1) removes the preceding '/'
  return null
}}/>
Sam Mckay
  • 61
  • 3
1

I went through the same issue. I want my portfolio to redirect to social media handles. Earlier I used {Link} from "react-router-dom". That was redirecting to the sub directory as here,

enter image description here

Link can be used for routing web pages within a website. If we want to redirect to an external link then we should use an anchor tag. Like this,

enter image description here

0

FOR V3, although it may work for V4. Going off of Eric'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:

import RedirectOnServer from './components/RedirectOnServer';

       <Route path="/somelocalpath"
          component={RedirectOnServer}
          target="/someexternaltargetstring like cnn.com"
        />

And the Component:

import React, { Component } from "react";

export class RedirectOnServer extends Component {

  constructor(props) {
    super();
    //if the prefix is http or https, we add nothing
    let prefix = window.location.host.startsWith("http") ? "" : "http://";
    //using host here, as I'm redirecting to another location on the same host
    this.target = prefix + window.location.host + props.route.target;
  }
  componentDidMount() {
    window.location.replace(this.target);
  }
  render(){
    return (
      <div>
        <br />
        <span>Redirecting to {this.target}</span>
      </div>
    );
  }
}

export default RedirectOnServer;
Eric Hodonsky
  • 4,117
  • 3
  • 22
  • 36
MattC
  • 4,968
  • 1
  • 42
  • 37
0

I'm facing same issue. Solved it using by http:// or https:// in react js.

Like as: <a target="_blank" href="http://www.example.com/" title="example">See detail</a>

-1

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):

redirectToHomePage = (): null => {
    window.location.reload();
    return null;
  };    
<Route exact path={'/'} render={this.redirectToHomePage} />

Where you could instead also use window.location.assign(), window.location.replace() etc

chezwhite
  • 540
  • 6
  • 8
-1

you can use this way in React to move to another website

var link="www.facebook.com"
<a href={"https://"+link} target="/blank">target Button</a>
-2

If you are using server side rending, you can use StaticRouter. With your context as props 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').

Rei Dien
  • 546
  • 2
  • 12
  • I'm asking for a way to do it in the client. It actually should be done at the DNS level if done correctly. Second would be in the initial server request. Since I'm hosting on S3, there is no server-side. SO I'm stuck for now until our dev-ops guy can do the redirect at the Service Level. – Eric Hodonsky Mar 23 '17 at 22:34
  • what you can do is, `` – Rei Dien Mar 23 '17 at 22:39
-2

You can now link to an external site using React Link by providing an object to to with the pathname key:

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

If you find that you need to use JS to generate the link in a callback, you can use window.location.replace() or window.location.assign().

Over using window.location.replace(), as other good answers suggest, try using window.location.assign().

window.location.replace() will replace the location history without preserving the current page.

window.location.assign() will transition to the url specified, but will save the previous page in the browser history, allowing proper back-button functionality.

https://developer.mozilla.org/en-US/docs/Web/API/Location/replace https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

Also, if you are using a window.location = url method as mentioned in other answers, I highly suggest switching to window.location.href = url. There is a heavy argument about it, where many users seem to adamantly want to revert the newer object type window.location to its original implementation as string merely because they can (and they egregiously attack anyone who says otherwise), but you could theoretically interrupt other library functionality accessing the window.location object.

Check out this convo. It's terrible. Javascript: Setting location.href versus location

WebWanderer
  • 7,827
  • 3
  • 25
  • 42
-5

I was able to achieve a redirect in react-router-dom using the following

<Route exact path="/" component={() => <Redirect to={{ pathname: '/YourRoute' }} />} />

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 app http://myapp.com/newplace. so the above helped.

walecloud
  • 151
  • 1
  • 4
  • 2
    The OP clearly states that he's trying to redirect to an external resource, not to a route inside the same app. – Neets Mar 14 '19 at 17:00
  • Clearly, I was specific about my use case and dropped that if he could apply it to his. my solution says within my app, he could use that as an example. – walecloud Mar 19 '19 at 03:11
  • 1
    If you want to showcase your use case to people, please write a blog about it. Stackoverflow is for answering the query that people have, not your use-case. Also, the right way to implement your use case is - – Abhas Aug 05 '20 at 21:16