Table of contents
In this post we will be learning how to create active links using React Router V6.4 .
Check out this post on my blog too!
Active links are commonly used in navigation bars to indicate the user's current page. React Router V6.4 introduces a new and simplified way to achieve this.
Note: This feature is only possible with data routers.
Creating the Routes
In this example, we will be using the createBrowserRouter
hook. First, let's create several routes in our App.js file.
import React from "react";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import "./App.css";
import Home from "./Pages/Home";
import Blog from "./Pages/Blog";
import About from "./Pages/About";
import Contact from "./Pages/Contact";
import Root from "./Root";
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
children: [
{
path: "/",
element: <Home />,
},
{
path: "/blog",
element: <Blog />,
},
{
path: "/about",
element: <About />,
},
{
path: "/contact",
element: <Contact />,
},
],
},
]);
function App() {
return <RouterProvider router={router} />;
}
export default App;
React Router v6 replaces BrowserRouter with RouterProvider, which is a self-closing component that takes router as a prop. The Root element represents a page that will contain the Outlet
and the navigation bar. Individual routes can be specified in the children array. In the example above, the pages are simple React components with a heading.
Creating the Root Page
Next up we will create the Root page:
import React from "react";
import { NavLink, Outlet } from "react-router-dom";
function Root() {
return (
<div className="App">
<nav>
<NavLink to="/">Home</NavLink>
<NavLink to="/blog">Blog</NavLink>
<NavLink to="/about">About</NavLink>
<NavLink to="/contact">Contact</NavLink>
</nav>
<main>
<Outlet />
</main>
</div>
);
}
export default Root;
The <Outlet>
component is used in parent route elements to render their child route elements, which represent the pages in our case. In addition, we have added NavLinks to enable navigation between the pages."
Adding active classes
Our implementation of the component includes an isActive property which holds a boolean value. By providing a function to the className attribute when we use our NavLink component, we can access this property and conditionally apply styles based on whether the NavLink is currently active or not.
<NavLink
to="/blog"
className={({ isActive }) => (isActive ? 'active' : '')}
>
Blog
</NavLink>
And in the App.css file:
nav a.active{
color: green;
}
A demo is provided below:
Thanks for Reading. Check out my blog too!