Icon
Get In Touch
#nextjs

Navigation Links with Active State in Next.js

This documentation will guide you through creating navigation links with an active state in a Next.js application.

Links Component

Create a file named Links in the components directory and add the following code:

1
"use client";
2
3
import Link from "next/link";
4
import { usePathname } from "next/navigation";
5
import React from "react";
6
import styles from "./Links.module.css";
7
8
function Links() {
9
const Links = [
10
{
11
title: "Home",
12
url: "/#top",
13
},
14
{
15
title: "About",
16
url: "/#about",
17
},
18
{
19
title: "Services",
20
url: "/#services",
21
},
22
{
23
title: "Projects",
24
url: "/#projects",
25
},
26
{
27
title: "Contact",
28
url: "/#contact",
29
},
30
];
31
32
const pathname = usePathname();
33
34
return (
35
<>
36
{Links.map((link) => (
37
<Link
38
key={link.title} // Added a key prop to avoid React warnings
39
href={link.url}
40
className={`${styles.linknormal} ${
41
pathname === link.url && styles.linkactive
42
}`}
43
>
44
{link.title}
45
</Link>
46
))}
47
</>
48
);
49
}
50
51
export default Links;

Defines a list of links with titles and URLs. Uses usePathname to get the current path. Maps through the links array. Applies conditional CSS classes to highlight the active link.

CSS Styling

Create a file named Links.module.css and add the following code and style accordingly:

1
.linknormal {
2
display: flex;
3
gap: 20px;
4
color: black;
5
}
6
7
.linkactive {
8
font-weight: 600;
9
color: red;
10
}

Defines .linknormal class for default link styling. Defines .linkactive class for styling the active link.

Import and use the Links component

By following these steps, you can create a set of navigation links in Next.js that visually indicate which link is currently active based on the URL.

©2024 Codeblockz

Privacy Policy