Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v4 <NavLink> vs <Link> benefits

People also ask

Should I use NavLink or link?

Conclusion. 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.

Why we use NavLink in React?

The <Link> and <NavLink> are the components provided by react-router-dom to navigate around the react application. Generally, we use anchor tags for this purpose while navigating.

What is the difference between link and useNavigate?

The difference between the Link (and NavLink and Navigate ) components and the navigate function returned by the useNavigate hook is effectively the same difference between Declarative and Imperative programming.

What is the use of link in React Router?

A <Link> is an element that lets the user navigate to another page by clicking or tapping on it. In react-router-dom , a <Link> renders an accessible <a> element with a real href that points to the resource it's linking to.


The official documentation is clear:

<NavLink>

A special version of the <Link> that will add styling attributes to the rendered element when it matches the current URL.

Thus, the answer is NO. There are no other reasons except the mentioned one.


When you need to use style or class attributes on active <Link>, then you can use <NavLink>

Let see the example:

Link

<Link to="/">Home</Link>

NavLink

<NavLink to="/" activeClassName="active">Home</NavLink>

Link Component

It is used to create links which allow to navigate on different URLs and When we click on any of that particular Link, it should load that page which is associated with that path without reloading the page. Example:

enter image description here

NavLink Component:

If, we want to add some styles to the Link. So that when we click on any particular link, it can be easily identified which Link is active. For this react router provides NavLink instead of Link. Now replace Link from Navlink and add properties activeStyle. The activeStyle properties mean when we click on the Link, it should be highlighted with different style so that we can differentiate which link is currently active. Example:

enter image description here

Ref: https://www.javatpoint.com/react-router


Simply, When you use <Link> there isn't any active class on selected element.
In contrast, with <NavLink> the selected element is highlighted because this element is added an active class.
Hope useful for you.