I have a React 18 application and I am using the react-router-dom version 6.24.1. I am getting confused as to when I should use the <Link />
tag and when I should use the <a>
(anchor) tag in a React app?
Is the <Link />
tag to be used for navigation within the application only? And is the anchor tag used for external links outside the app? Please see the below code:
Menu.jsx
file:
import { Link } from "react-router-dom";
const Menu = () => {
const padding = {
paddingRight: 5
}
return (
<div>
<Link to="/" style={padding}>anecdotes</Link>
<Link to="/create" style={padding}>create new</Link>
<Link to="/about" style={padding}>about</Link>
</div>
);
}
Footer.jsx
file:
import { Link } from "react-router-dom";
const Footer = () => (
<div>
Google search for <Link to='https://www.google.com/' target="_blank">Google</Link>.
or
Google search for <a href='https://www.google.com/' target="_blank">Google</a>.
</div>
);
How do I decide when to use the Link
tag and the anchor tag? What is the best practice?
<Link>
change the URL without causing full page reload. This allows for smoother transitions and maintains the state of the application.
<a href="...">
Standard HTML element for navigation, It causes a full page reload, even if the destination is within the same application. This can be useful for external links or when you need to ensure a full reload of the page.