#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";23import Link from "next/link";4import { usePathname } from "next/navigation";5import React from "react";6import styles from "./Links.module.css";78function Links() {9const Links = [10{11title: "Home",12url: "/#top",13},14{15title: "About",16url: "/#about",17},18{19title: "Services",20url: "/#services",21},22{23title: "Projects",24url: "/#projects",25},26{27title: "Contact",28url: "/#contact",29},30];3132const pathname = usePathname();3334return (35<>36{Links.map((link) => (37<Link38key={link.title} // Added a key prop to avoid React warnings39href={link.url}40className={`${styles.linknormal} ${41pathname === link.url && styles.linkactive42}`}43>44{link.title}45</Link>46))}47</>48);49}5051export 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 {2display: flex;3gap: 20px;4color: black;5}67.linkactive {8font-weight: 600;9color: 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