by Sai gowtham

How to redirect to external URL in React Router

In this tutorial, we are going to learn about how to redirect to an external URL in React Router.

Suppose we have a /contact route in our react app, when a user visits the /contact page we need to redirect them to an external url https://www.google.com/contact/ instead of the same domain redirect.

Redirecting to external URL

To redirect to an external url in React, we can use the window.location.href property.

Here is an example:

Contact.js
import React, { useEffect } from "react";

function Contact() {

  useEffect(() => {
    window.location.href = "https://google.com/contact";  }, []);

  return (
    <div>
      <h2>Contact</h2>
    </div>
  );
}

export default Contact;

In the above code, we first imported the useEffect() hook from the react package and run it inside the Contact component function by adding a window.location.href = "https://google.com/contact".

Now, if a user tries to visit the /contact page he or she will be redirected to https://google.com/contact.

Note: The useEffect() hook with a second argument empty [] array acts like componentDidMount lifecycle method in class components.

Similarly, you can also redirect to an external url inside the class-based components like this:

Contact.js
import React from 'react';

class Contact extends React.Component {
 componentDidMount(){     window.location.href = "https://google.com/contact";  }
  render() {
    return (
      <div>
       <h2>Contact</h2>
      </div>
    )
  }
}

export default Contact;

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course