Author -  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;

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY