Problem Encountered with Modifying Active Link Color in Next.js Following Introduction of Multiple Root Layouts

Currently, I am in the process of developing an application with Next.js and incorporating multiple root layouts from the official documentation at https://nextjs.org/docs/app/building-your-application/routing/creating-multiple-root-layouts. This was necessary for me to style each route uniquely.

However, upon implementing these multiple root layouts, I came across a problem where the active link's color is not changing as expected, despite it working perfectly fine before the changes were made.

Admittedly, I am still a beginner, and finding comprehensive information on the latest versions of Next.js can be quite challenging.

Below is the part of the code where I handle the active link color:

import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";

const Sidebar = () => {
    const [isMobileMenuVisible, setIsMobileMenuVisible] = useState(false);
    const pathname = usePathname();

    const isActive = (href) => {
        if (pathname.startsWith(href)) {
            return "text-[#909090]";
        }
        return "";
    };

    const toggleMobileMenu = () => {
        setIsMobileMenuVisible(!isMobileMenuVisible);
    };

    return (
         DACHI-GIORGI GARUCHAVA
         {/* Mobile dropdown menu */}
         <button
            className="text-[#484848] no-underline cursor-pointer font-MPlus1 leading-6 font-thin tracking-wider mb-2"
            onClick={toggleMobileMenu}
            Menu
            {isMobileMenuVisible && (
                The Witness
               {/* Add other links here */}
            )}
           {/* Desktop link list */}
           Invasive Modification
           {/* Add other links here */}
       );
};

export default Sidebar;

The isActive function examines the pathname to determine the activity of the link and assigns a specific text color accordingly. This functionality worked flawlessly until I implemented multiple root layouts, which are essential for customizing individual routes.

I would greatly appreciate any assistance or guidance in resolving this issue.

Answer №1

After testing the GitHub repository you shared on codesandbox, it seems like the issue is not related to root layouts. Your isActive method is functioning correctly and is indeed adding the text-[#909090] class name to your HTML markup.

The main issue lies in the fact that you defined a custom class called project_link using the @apply directive, and the color specified in that class is overriding the color applied through text-[#909090]. Here's a screenshot of the markup for reference:

https://i.stack.imgur.com/Isiw1.png

To resolve this problem effectively, it's recommended not to use the class abstraction created with project_link but instead apply classes inline directly, conditionally setting the color based on whether the link is active or not. Creating abstractions like these goes against the purpose of utilizing tailwind, as mentioned in their documentation regarding avoiding premature class abstractions.

If you wish to minimize duplication, a better approach would be to create a separate component for these links where isActive is passed as a prop from the parent component. Within that separate component, you can apply the class like this:

  ...
  className={`no-underline cursor-pointer font-MPlus1 leading-6 font-thin tracking-wider ${isActive ? 'text-[#909090]' : 'text-[#484848]'}`}
  ...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Concentrate on the HTML element once it becomes active

I am facing a challenge where I need to focus on a specific input element. However, there is a spinner that appears on page load and remains hidden until certain http requests are completed. All inputs are disabled until the requests are finished. The setu ...

I am trying to showcase a collection of images on my homepage, but unfortunately, it is not functioning as expected

Does anyone know how to display images using Angular? I am currently utilizing the pic controller in an AngularJS file. Any assistance would be greatly appreciated. HTML CODE <!DOCTYPE html> <html> <head> <meta charset="utf-8"& ...

Impact of Jquery on dropdown menus in forms

Currently, I have a script for validating form information that adds a CSS class of .error (which includes a red border) and applies a shake effect when the input value is less than 1 character. Now, I also need to implement this validation on various sel ...

Drag and drop a Jquery image onto the div with its top left corner

Drop targets: <div id="targetContainer" style="width:100px; height:100px;> <div id="tar_0-0" class="target" style="position: relative; float:left; width:50px; height:50px; background-color: #fff;"></div> <div id="tar_1-0" class="t ...

Contrasting the utilization of async and return new Promise

I am struggling to call an async utility function from my NextJS API page, but I keep getting undefined as the result. When I visit localhost:300/api/hello, the console displays the following: result = undefined In my File 1 (api/hello.js), here is the c ...

I'm attempting to create a button using html, but I'm puzzled as to why it's not functioning as expected

I've been working on creating a button that, when pressed, generates a new div string based on the node.innerHTML code. For some reason, my code doesn't seem to be functioning properly and I'm not sure why. Here's the HTML: <input ...

I encountered an issue while trying to use jshint with a simple hello world script, receiving the error message: "line 0, col 0, Bad option: 'script'."

This is a basic introduction to my coding journey. function greet() { return 'Hello world'; } Here is the jshint setup I am using: { "browser": true, "browserify": true, "devel": true, "script" ...

What is the process for utilizing GruntFile.coffee and package.json to extract or create the Lungo.js example files?

I want to experiment with the Lungo.js examples found here: https://github.com/tapquo/Lungo.js. However, when I try to run the index.html in the example directory, it seems like the components and package directories are empty. Although these directories d ...

Looking to divide a multiple-page .TIFF document into several PNG or JPG files using the sharp module in node.js?

Is there a way to split a single .tiff file with multiple pages into several .png or .jpg files without using ImageMagick or GraphicsMagick due to limitations in my codebase? I am unable to install CLI tools so I'm exploring alternate solutions. I kn ...

Error: The JavaScript SRC cheat is malfunctioning

Having an issue with the code below. The 'dummy1' and 'dummy2' variables are not loading their content as expected on the page. Any suggestions? <html> <head> <title>JavaScript On-line Test</title> <script LA ...

Accessing specific elements within multi-dimensional arrays using JavaScript

I've embarked on the exciting journey of creating my own 'Choose Your Adventure!' game, but I've hit a snag. I'm struggling to effectively target specific values within the multi-dimensional array I constructed. In order to add som ...

ES6 Generators: lack of informative stack trace when using iterator.throw(err)

The ES6 approach: iterator.throw(err) is often explained as inserting an exception as if it happened at the yield statement within the generator. The challenge lies in the fact that the stack trace of this exception does not include any information about t ...

Validate forms using jQuery with the power of ajax

Is there a way to effectively check for the existence of a username? I want to increment a variable called "form_error" if the username already exists. If "form_errors" is greater than 0, I need the code to stop and return false. However, when I use an Aj ...

Guide to Returning a Unique Error Message when Verifying Credentials with Next-Auth v5.0.0-beta.5

Currently, in my nextJs app, I am using [email protected] for user authentication. I am looking to implement custom error handling for failed user authentication with credentials. In the past, I was able to achieve this functionality with the followi ...

Can Capacitor be integrated with the latest NextJS 13's "/app" architecture?

I'm experiencing challenges with implementing Capacitor in my NextJS 13 project that utilizes the new App router. Is there a way to generate an "out" folder and an "index.html" file when building the application while following the new "/app" structu ...

Switch up the text when the image link is being hovered over

Is there a way to change the text color of the "a" tag when it is not wrapping the img link? <li> <a href="# WHEN I HOVER THIS IMG LINK I WANT A TAG BELOW TO CHANGE COLOR"> <img alt="Franchise 16" src="#"></img> < ...

Managing array elements in React: removing and duplicating items

One of my tasks is to incorporate a copy and delete button within a table. My goal is to pass the index from the map to the delete and copy onclick functions, however, I am encountering an issue where copying a row results in it having the same index as th ...

Is there a way to showcase a block of Python code using a combination of HTML, CSS, and Javascript to enhance its

On my website, I want to display code blocks similar to how StackOverflow does it. The code block should be properly colored, formatted, and spaced out for better readability. All the code blocks on my site will be in python. def func(A): result = 0 ...

There was an error encountered: TypeError - show.visible cannot be iterated upon. This issue might be related to

I am facing an issue while using React's functional component to update the state. My intention was to fetch data and display the first 10 items, followed by a "load more" button which would reveal another set of 10 items upon clicking. Can someone as ...

When you click on the button, the section will not be displayed

I'm facing an issue with my code. I have a set of five buttons and corresponding sections. When a button is clicked, the active and active-btn classes are supposed to be added to that button as well as the corresponding section element with the same i ...