0
0
NextJSframework~30 mins

Active link detection in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Active link detection
📖 Scenario: You are building a website with a navigation menu. You want the menu to show which page is currently active by highlighting the active link.
🎯 Goal: Create a navigation bar in Next.js that highlights the active link based on the current page URL.
📋 What You'll Learn
Create a list of navigation links with exact paths
Set up a variable to get the current path using Next.js router
Use conditional logic to add an active class to the link matching the current path
Add the active class to the correct <a> element in the navigation
💡 Why This Matters
🌍 Real World
Websites often highlight the current page in their navigation menus to help users know where they are.
💼 Career
Knowing how to detect and style active links is a common task in frontend development and improves user experience.
Progress0 / 4 steps
1
Create navigation links
Create a constant called navLinks that is an array of objects. Each object should have name and path keys with these exact values: { name: 'Home', path: '/' }, { name: 'About', path: '/about' }, { name: 'Contact', path: '/contact' }.
NextJS
Need a hint?

Think of navLinks as a list of pages with their names and URLs.

2
Get current path from Next.js router
Import useRouter from next/router and create a constant called router by calling useRouter(). Then create a constant called currentPath that gets the pathname from router.
NextJS
Need a hint?

Use Next.js useRouter hook to get the current page path.

3
Add active class conditionally
Use navLinks.map to create a list of <a> elements. For each link, add a className that is 'active' if link.path === currentPath, otherwise an empty string ''. Use link.name as the link text and link.path as the href.
NextJS
Need a hint?

Use className with a condition to highlight the active link.

4
Add CSS for active link
Add a <style jsx> block inside the Nav component. Define the .active class to have color: red; and font-weight: bold; so the active link stands out.
NextJS
Need a hint?

Use Next.js scoped CSS with <style jsx> to style the active link.