How do I link to an external URL in React?
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;
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
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.
Random Code Snippet Queries: React
- Module not found: Error: Can't resolve 'prop-types'
- Uncaught Error: useHref() may be used only in the context of a <Router> component
- Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead
- We're unable to detect target browsers. react app
- React-dom.development.js:86 Warning: validateDOMNesting(...):
- Get the ID from a URL in React and React Router
- Module Not Found: Can’T Resolve ‘Jquery’ In React
- How to pass dynamic URL to Link in react ?