How to Redirect to External URL in React

Rana Hasnain Khan Feb 02, 2024
How to Redirect to External URL in React

We will introduce how to redirect to an external URL in React.

Redirect to External URL in React

Whenever we want to redirect to another path, we can change the state to re-render the component. But sometimes, we may need to redirect to some external URL.

To understand the redirection to an external URL, we will show an example.

In this example, we will create a navigation menu that will redirect the user to some external link. First, we will create a div with class root in the index.html file.

# react
<div id="root"></div>

Next, we will import React, render, and BrowserRouter.

# react
import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

Then, we will create a menu.

# react
const Menu = () => (
  <div>
    <ul>
      <li>
        <Link to="/privacy-policy">privacy</Link>
      </li>
    </ul>
  </div>
);

Now in render(), we will return a redirection router. The code in index.js will look like this.

# react
import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

const Menu = () => (
  <div>
    <ul>
      <li>
        <Link to="/privacy-policy">privacy</Link>
      </li>
    </ul>
  </div>
);

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
    };
  }

  render() {
    return (
      <Router>
        <div>
          <Menu />
          <Route
            path="/privacy-policy"
            component={() => {
              window.location.replace('https://example.com/1234');
              return null;
            }}
          />
        </div>
      </Router>
    );
  }
}

render(<App />, document.getElementById('root'));

Output:

react redirect

Whenever a user clicks on the privacy menu, it will be redirected to an external URL.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn