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