NavLink is consistently marking all links as active, unfortunately, none of the suggested solutions on Stack Overflow have proven

I have tried multiple solutions found elsewhere without success, so I am reaching out for help. I am struggling to render NavLinks differently based on whether they are active or not. I followed the ternary operator logic from the react-router-dom documentation for NavLinks but cannot get it to work as expected. Initially, I considered creating a function to avoid repeating code three times, but first, I need to resolve the rendering issue.

(side question: why does removing the Router tags from the return statement cause a break? Initially, I used regular routes before styling the NavLinks differently and had to add Router tags. Without them, I encounter an error related to useHref)

Below is my return statement along with the styled-components:

return (
        <>
            <GlobalStyles />
            <Router>
                <Header />
                <Wrapper>
                    <NavBar>
                        <NavLink
                            to="/search"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Search song
                        </NavLink>
                        <NavLink
                            to="/weekly-thread"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Weekly thread
                        </NavLink>
                        <NavLink
                            to="/game"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Game
                        </NavLink>
                    </NavBar>
                </Wrapper>
            </Router>
        </>
    );
};

const Wrapper = styled.div`
    width: 100vw;
    height: 100vh;
    position: absolute;
    z-index: -1;
`;
const NavBar = styled.div`
    display: flex;
    padding: 20px 20px;
    position: relative;
    gap: 20px;
    font-size: 18px;
    a {
        text-decoration: none;
    }
    .nav-link {
        color: blue;
        &:inactive {
            color: black;
        }
    }
`;

EDIT: The situation has become even stranger. After pasting the provided code solution and seeing no changes, I attempted to adjust the font size for the active NavLink. Surprisingly, only the second and third elements were affected while the first one remained unchanged in terms of appearance. When clicking on other NavLinks, the URL updates but their styles stay inconsistent.

SECOND EDIT: Trying to troubleshoot further, I added console logs to one of the NavLinks:

<NavLink to="/search" exact className={(isActive) => {
    console.log(isActive);
    isActive === false ? console.log(isActive) : console.log("foo");
}}>Search song</NavLink>

The first console log correctly shows the value of isActive, but the subsequent ones always display "foo," regardless of the condition. Even swapping "isActive === false" to "isActive === true" does not change this unexpected behavior. This issue is perplexing me.

Answer №1

While debugging with console.logs scattered throughout the code, a peculiar observation caught my eye: isActive was displaying as an object in the console. This realization explained why I kept receiving consistent results.

Upon adjusting the condition in the ternary operator to isActive.isActive ?, I finally began to see the anticipated outcomes.

Answer №2

Router

For a better understanding, it is recommended to refer to the documentation.
The primary components page elaborates on the significance of using a router.
It also provides insights into other components, such as identifying the current route.

NavLink

NavLinks have the capability to manage their own active class by checking if the router matches the to props of the respective NavLink element.

Refer to this CodePen for a practical demonstration.

Keep in mind that you may still need to define the CSS styling for the applied class. If you are utilizing frameworks like bootstrap or material-ui, they often include a default .active CSS style.

CSS

The CSS rule appears to have a mistake - there is a colon at &:inactive which should likely be represented as .inactive:

.nav-link {
    color: blue;
    &.inactive {
      color: black;
    }
  }

Check out this codepen example.

Answer №3

To enhance your NavLink component, consider removing the className property.

Simply remove this code snippet:

className={(isActive) =>
    "nav-link" + (!isActive ? " inactive" : "")
}>

It's redundant since React-Router automatically applies the .active class to active links, so using that property might be causing unexpected behavior.

You can instead customize the styling of the a.active element as needed.

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

Is there a way to create 3 divs in the first row and 2 divs in the second row?

How do I create 3 divs in the first row and 2 divs in the second row? This is what it currently looks like: This is the desired output: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity= ...

After deploying the Next.js application, an error occurred: "Page requested does not match resolved page

After deploying to the server, I am frequently encountering errors like this: Error: Requested and resolved page mismatch: //pipe/31c28e30-fd19-4130-ac0c-32d155841c12/_next/static/jh1CfGVGeGbuBSqLYny_c/_middlewareManifest.js /pipe/31c28e30-fd19-4130-ac0c-3 ...

What is the best way to iterate through states within an array using React?

Can someone help me create a button that can cycle through different states in the given array? I want the button to change State_1 to State_2, State_2 to State_3, and then back to State_1 for each object. I'm struggling to figure out how to cycle thr ...

The hamburger symbol (&#9776;) appears as a dull shade on Android screens

Imagine a basic website design featuring a gray background with white text. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> </head> <body style="background: gray; color: white; font-size:50px;" > The t ...

Learn how to properly render option values in React-select by excluding any that are undefined

I have a requirement to display my `Option` values based on conditions using `if/else` statements. The rendering should only show options that are related to the parameter from the query. const renderList = useMemo(() => { return mediaCategories?.En ...

What is the optimal way for text selection to operate within a clickable component on a web application?

We're currently developing a web application with expandable/collapsible elements. Here's an example of one of the clickable items: https://i.stack.imgur.com/jdLOu.png The text selection behavior when clicking on the element is causing some an ...

What could be causing issues with my application when using server-side rendered styled-components with Next.js?

I am in need of assistance with an error I've encountered. Every time I try to access the homepage of my Next.js app, it breaks and displays a cannot read data map of undefined error. The browser consistently directs me to the _document.js file, but I ...

Make a checkbox appear disabled while still allowing it to be checked and submit its value

I have a checkbox that is dynamically updated based on user selections, and it is crucial to show the checked status to the user. However, I also want it to be restricted in terms of functionality while still indicating its checked state visually. One ...

How should image dimensions for a background image be properly specified in CSS?

In my CSS file, I have defined styles for mini icons like this: /* Total counts - mini icons */ span.count-facebook { background: #fff url(../images/mini-icons/facebook.png) no-repeat 1px center; } span.count-plusone { background: #fff url(../images/mini- ...

Accessing nested keys within an object and comparing them to keys within another object, with the distinction that the second object contains an array of objects

I encountered a challenge while trying to compare and access data within nested objects and match them with an array of non-nested objects. To illustrate, the scenario looks something like this: const members = [ { name: 'Angelica&apos ...

Changing direction of arrow upon dropdown menu opening with JavaScript

I have developed a piece of code that enables users to click on a div in order to reveal a dropdown menu containing radio buttons. My goal is to make the arrows rotate 180 degrees when the dropdown menus are opened, and then return to their original positi ...

The cache of React query fails to persist after using queryClient.setQueryData

Why is React query not maintaining its cache after queryClient.setQueryData? It also appears to be not working on defaultOptions as shown below. I have been using the React query developer tool which indicates that the data is stored after an API call, but ...

The constricted styles are causing the whole page to bounce (scroll) up and down

On my SPA frontend, I have a parent div with a height of 580 containing 9 smaller divs (about 190px in height each). The parent div has an overflow set to hidden so that only 3 elements are visible at one time. Every 5 seconds, I change the styles by addin ...

Ways to eliminate the influence of parent containers on child controls

Q: I'm encountering an issue with my date picker implementation using RadDatePicker within a table td and multiple containers (div). The problem arises from the navigation text being reversed - ">>" instead of "<<", ">" instead of "< ...

What steps can be taken to resolve the no-unused-vars issue in NodeJS?

Seeking assistance with a todo app development project using the MERN stack. Being relatively new to this technology, I am encountering an error that I cannot seem to resolve. Below is the code for both my app.js and todo.js files. Despite thorough inter ...

tips for updating <h1> elements using ghcjs-dom

My experience with the ghcjs and ghcjs-dom documentation has been quite limited. Here is a simple example with basic HTML code: h1 { font-family: Helvetica; } p {font-family: Helvetica; color: blue; } <h1> Hello World </h1> <p> This i ...

Tips for aligning buttons vertically within the form-row class in Bootstrap 4

I'm facing an issue where I cannot get a set of buttons in line with labels when using different column widths in Bootstrap. The behavior of a button assigned to a specific column width, like col-3, is not the same as a button assigned with automatic ...

Browsed through the CSS impact panels

.Tab1 { background-image: url("http://dl.dg-site.com/wp-content/themes/aeron/images/dl-products-icons5.jpg"); background-repeat: no-repeat; background-position: center; background-clip: content-box; width: 100px; height: 75px; display: block; ...

Troubles with applying Global Themes in StyledComponents for React Native

Problem with Global Theme in StyledComponents (React Native) When attempting to utilize a color from my global theme in my component and setting it like so: background-color: ${({theme}) => theme.} The properties within theme, such as colors, font-siz ...

What is the most concise way to align one table row in the middle and another at the top?

Is there a way to align different rows in a table vertically with minimal code? I have a table with 3 rows, and I want the first two rows to be aligned vertically to the top, while the third row should be vertically aligned to the middle. If I try to def ...