How do I link to an external URL in React?

Created at 06-Dec-2022 , By samar

You can use the Link component or an HTML anchor tag if you want to redirect to an external link with React Router. Using the <Link> component, you can do it. It will redirect the user to the specified URL.

Anchor tag to open a external link in new tab.

<a href="https://w3codegenerator.com" target="_blank">
	Click to open (new tab)
</a>

You can do that in plain JavaScript by calling window.location.replace() method.

window.location.replace('https://w3codegenerator.com');

To navigate to external Link, set the window.location.href property. It will redirect you to a new external link.

 window.location.href = 'https://w3codegenerator.com';

You can call a function on click button to redirect url to an external link in react. You have to define a function and you have to call the function on click button. Here we have a demo code to illustrate the example.

src\App.js

import React from 'react';

export default function App() {
  const redirectto = () => {
    window.location.href = "https://google.com/contact";
  }
  return (
    <div className="App">
      <button onClick={redirectto}> Go to google </button>
    </div>
  );
}
  • Add external Link using react-external-link library

    You have to install the external link package and after that you can use it to opne external link in your react app.

    npm install react-external-link --save
    
    //add dependency using yarn 
    yarn add react-external-link
    
    import React from 'react';
    import { ExternalLink } from 'react-external-link';
    
    const App = () => (
      <div>
        <ExternalLink href="https://w3codegenerator.com" />
      </div>
    );
    
    export default App;
    

Back to code snippet queries related react

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.