xxxxxxxxxx
import * as React from "react";
import { NavLink } from "react-router-dom";
function NavList() {
// This styling will be applied to a <NavLink> when the
// route that it links to is currently selected.
let activeStyle = {
textDecoration: "underline",
};
let activeClassName = "underline";
return (
<nav>
<ul>
<li>
<NavLink
to="messages"
style={({ isActive }) =>
isActive ? activeStyle : undefined
}
>
Messages
</NavLink>
</li>
<li>
<NavLink
to="tasks"
className={({ isActive }) =>
isActive ? activeClassName : undefined
}
>
Tasks
</NavLink>
</li>
<li>
<NavLink to="tasks">
{({ isActive }) => (
<span
className={
isActive ? activeClassName : undefined
}
>
Tasks
</span>
)}
</NavLink>
</li>
</ul>
</nav>
);
}
xxxxxxxxxx
What is the difference between the NavLink and Link?
The NavLink is used when you want to highlight a link as active.
So, on every routing to a page, the link is highlighted according
to the activeClassName.
Link is for links that need no highlighting. And a is for external links.
xxxxxxxxxx
// Navbar.js
import React from "react";
// import { Link } from "react-router-dom";
import { NavLink } from "react-router-dom";
const Navbar = () => {
const navLinkStyles = ({ isActive }) => {
return {
fontWeight: isActive ? "bold" : "normal",
textDecoration: isActive ? "none" : "underline"
};
};
return (
<nav className="primary-nav">
{/* <Link to="/">Home</Link> */}
{/* <Link to="/about">About</Link> */}
<NavLink style={navLinkStyles} to="/">
Home
</NavLink>
<NavLink style={navLinkStyles} to="/about">
About
</NavLink>
</nav>
);
};
export default Navbar;
xxxxxxxxxx
What is the difference between NavLink and Link ?
the Link component is used to navigate the different routes on the site.
But NavLink is used to add the style attributes to the active routes.