Let’s explore various ways to redirect to external URL in React. Some of these are obvious, some are not.

Redirect to external URL in React

react-router library

As React developer, you may be tempted to use react-router for navigation. But React-router only works for internal navigation between pages on your single page application. It can not be used to redirect to external URL.

For this reason, we’ll use general JavaScript methods and properties accessible on the window interface.

Without further ado, let’s get started.  

window.location.replace()

As you know, all web apps have access to window interface. location object on this interface represents current URL in the browser. The replace() method simply changes current URL.

You can access window.location and call replace() method anywhere in your React component. For example, you can use it to handle a click event and redirect users to external url in response to clicks.

Let’s look at how to redirect to external URL when the button is clicked:

function App() {
  return (
    <div className="App">
      {/* Current page is not saved in hustory, users can't go back*/}
      <button onClick={() => window.location.replace("https://google.com")}>
        Redirect
      </button>
      <br />
      <br />
      {/* Current page is saved in hustory, users can go back*/}
      <button onClick={() => (window.location.href = "https://google.com")}>
        Redirect
      </button>
    </div>
  );
}

You can also use logic to set a condition for when the method should be called.

Important: Redirect using window.location.replace() does not save current URL in session history, so users can’t use the ‘back’ button to go to previous page.

window.location.href

Alternative way to redirect to external URL is to set window.location.href property to the URL you want to redirect to.

For example, here’s how to use window.location.href to redirect to URL when handling the onclick event in React.

<button onClick={() => (window.location.href = "https://google.com")}>
        Redirect
</button>

Unlike the replace() method, setting the href property to a new URL creates a new entry in the history object, so users can go back to previous page.  

Redirect to external URL on button click

Sometimes you need to redirect to another URL, for example after a successful authentication, or after form is submitted.

Let’s go back to our example. We use both window.location.replace() method and window.location.href property to change current URL (redirect to another URL).

If you open the demo in new tab, you’ll see that both buttons indeed redirect to external URL (‘google.com’).

The only difference is that first button doesn’t allow you to go back, while the second does.

Alternatively, you can style a simple <a> tag to look like a button. By default, <a> elements take users to specified URL.