Implementing Routing With the NavLink Element
Learn to implement NavLink using react-router in the React application.
We'll cover the following...
The NavLink
is better for styling links than the Link
component. Since the application has a navigation bar, it’s best to use NavLink
to show different styles for active links.
Add the NavLink
component
Let’s open the Navbar.js file and add the following code:
import React from "react";import { NavLink } from "react-router-dom";const Navbar = () => {return (<div className="navbar"><NavLinkclassName={({ isActive }) => (isActive ? "active" : undefined)}to="/contacts">Contacts</NavLink><NavLinkclassName={({ isActive }) => (isActive ? "active" : undefined)}to="/search">Search</NavLink></div>);};export default Navbar;
Add NavLink
Let’s review the code line by line. In ...