How to Redirect to an External URL in React?

Estimated read time 2 min read

In React, you can redirect to an external URL using the window.location.href property. Here’s an example of how to redirect to an external URL in React:

import React from "react";

function MyComponent() {
  const handleRedirect = () => {
    window.location.href = "https://www.example.com";
  };

  return (
    <div>
      <button onClick={handleRedirect}>Go to external URL</button>
    </div>
  );
}

In this example, we’re defining a component with a button that, when clicked, calls the handleRedirect function. This function sets the window.location.href property to the URL of the external site you want to redirect to.

When the button is clicked, the handleRedirect function will be called, and the browser will navigate to the external URL. Note that this will cause the current page to be unloaded and the new page to be loaded, which may not be desirable in all cases.

Also, keep in mind that redirecting to an external URL will take the user away from your React app, so you may want to provide some indication to the user that they will be leaving your site. You may also want to consider using a link with the target="_blank" attribute to open the external site in a new tab or window instead of redirecting the current page.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply