React navigation NavLink problem

After searching and attempting various solutions, I am still facing an issue with toggling the active className for a NavLink in my react-router-dom setup. Below is the code snippet:

import React from 'react'
import styles from './NavBar.module.css'
import logo from '../assets/logos/icon-left-font-monochrome-white.svg'
import { NavLink } from 'react-router-dom'

export default function NavBar() {
  return (
    <div className={styles.nav_contrainer}>
      <img className={styles.img} src={logo} alt='logo groupomania avec typo blanc' />
      <nav className={styles.nav}>
        <NavLink to='/home' exact='true' className={(navData) => (navData.isActive ? 'active' : 'none')} style={{ textDecoration: 'none' }}>
          <li>Home</li>
        </NavLink>

        <NavLink to='/articlebuilder' className={(navData) => (navData.isActive ? 'active' : 'none')} style={{ textDecoration: 'none' }}>
          <li>Écrire un article</li>
        </NavLink>

        <NavLink to='/profile' className={(navData) => (navData.isActive ? 'active' : 'none')} style={{ textDecoration: 'none' }}>
          <li>Profile</li>
        </NavLink>
      </nav>
    </div>
  )
}

The solution provided by others does not seem to work for me, despite trying the 'exact=true' attribute in all links. Here is how the paths are defined:

<div className='App'>
  <Routes>
    <Route path='/' exact={true} element={<HomePage />} />
    <Route path='/landingpage' exact={true} element={<LandingPage />} />
    <Route path='/home' exact={true} element={<HomePage />} />
    <Route path='/profile' exact={true} element={<Profile />} />
    <Route path='/articlebuilder' exact={true} element={<ArticleBuilder />} />
    <Route path='/signup' exact={true} element={<Signup />} />
    <Route path='/signin' exact={true} element={<Signin />} />
  </Routes>
</div>

Below is the accompanying CSS file:

.nav_contrainer {
  background-color: #ffac99;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0em 0em 0em 1em;
}

nav {
  display: flex;
  position: sticky;
}

nav a {
  list-style: none;
  font-size: 1.6em;
  color: white;
  transition: all ease-in-out 350ms;
  padding: 10px;
}

nav a:hover {
  color: #870e07;
  cursor: pointer;
}

.nav_contrainer img {
  width: 15%;
  height: 15%;
}

.active {
  color: #870e07;
  font-weight: bold;
}

Am I overlooking something crucial? Any help would be appreciated.

Answer №1

Make sure to add the active class to your class in the NavBar CSS module.

function NavBar() {
  return (
    <div className={styles.nav_container}>
      <img className={styles.img} src={logo} alt='logo groupomania with white typo' />
      <nav className={styles.nav}>
        <NavLink
          to="/home"
          className={(navData) => (navData.isActive ? styles.active : "none")}
          style={{ textDecoration: "none" }}
        >
          <li>Home</li>
        </NavLink>

        <NavLink
          to="/articlebuilder"
          className={(navData) => (navData.isActive ? styles.active : "none")}
          style={{ textDecoration: "none" }}
        >
          <li>Write an article</li>
        </NavLink>

        <NavLink
          to="/profile"
          className={(navData) => (navData.isActive ? styles.active : "none")}
          style={{ textDecoration: "none" }}
        >
          <li>Profile</li>
        </NavLink>
      </nav>
    </div>
  );
}

https://codesandbox.io/s/react-router-navlink-issue-mzep0d?fontsize=14&hidenavigation=1&initialpath=%2Fhome&module=%2Fsrc%2FApp.js&theme=dark

https://i.sstatic.net/GLyC0.png

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

Making adjustments to a Jquery data attribute can have a direct impact on CSS

My CSS is using a data attribute, but when I try to change it with jQuery, the change is not reflected on the screen or in the DOM. $('#new-1').data('count', 5); .fa-stack[data-count]:after { position: absolute; right: -20%; to ...

Enhance your obj model in React three fiber with the addition of textures

I am looking to incorporate texture into my app for loaded .obj models. The same issue arises with .fbx loaded models as well. Below is the code snippet I have been working on, but it seems to only work with something like sphereGeometry and not with a loa ...

Navigating between pages using React-router-dom

Just implemented a simple navigation using react-router-dom. Managed to get it working with this.props.history.push('/pathName'); But I'm not entirely sure if my understanding and approach are correct. Any advice on correcting my mistakes wo ...

Show the React component upon clicking the Add button

I recently developed a React component that reveals a new section whenever the user clicks the "New Section" button. However, I have encountered an issue - I would like the component to display multiple sections based on how many times the button is clic ...

Altering Image Order Across Various Slides

I have customized a parallax website template that is divided into various sections and slides. I want to incorporate a fixed image sequence on each slide that animates based on the scroll position. With 91 images in the animation sequence, it moves quickl ...

Chrome Extension with UMD Modules

The definition of the UMD module can be summarized as follows: (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['exports', ' ...

Guide to dividing the screen into three horizontal sections

I am currently working on a website and trying to divide a page into three different sections: one for the title and a button, one for the content, one for the text input. . The issue I'm facing is that the divs are not filling the height and ...

Changing a string into a dictionary using Javascript

Here is the data I have: d0 = "{\"a\":\"324jk324\",\"b\":\"42793bi42\",\"c\":\"894h42hi\"}" d = JSON.parse(d0) \\ g ...

After the upgrade to Material UI 4, I encountered an issue with the withStyles feature that is causing errors

After updating to MUI v4.0.2 from v3.9.x, I encountered this error: The function returned by connect requires a component to be passed. However, {"propTypes":{},"displayName":"WithStyles(MyComponent)","options":{"defaultTheme":{"breakpoints":{"keys":["x ...

Setting the || operator with JSX in React can be done by using the logical OR

Hi, I'm trying to configure two conditional statements using React. Here is the code I have: <div> {item?.status === "One" || (item?.status === "Two" && ( <Button btn="primary" title="One text" /> ))} &l ...

Leveraging multi-processing with NextJS and NodeJS

My tech stack includes NextJS for frontend development and NodeJS for backend development. I'm looking to implement child processes in my project. Could someone guide me on setting up NodeJS for this purpose? Additionally, I'm interested in utili ...

Can React Slick be configured to display a Carousel within another Carousel?

Can React Slick support a Carousel within another Carousel? import Slider from "react-slick"; <Slider {...settings} > <div/> <div> <Slider {...settings} > ...

Clicking on the checkbox will remove the selected text within the contenteditable div

My objective is to create a custom text editor with basic functionalities such as bold, italic, underline, and paragraph styling only. The purpose of this project is for studying purposes. The main challenge I am facing is avoiding color-based interaction ...

Attempting to retrieve data from an object by utilizing an external URL, however

Upon starting the bot console, the console displays: Online with undefined/5 After 10 seconds, an error is thrown: undefined:1 [object Promise] ^ SyntaxError: Unexpected token o in JSON at position 1 This is the code snippet being used: let players clie ...

Swap out a portion of HTML content with the value from an input using JavaScript

I am currently working on updating a section of the header based on user input from a text field. If a user enters their zip code, the message will dynamically change to: "GREAT NEWS! WE HAVE A LOCATION IN 12345". <h4>GREAT NEWS! WE HAVE A LOCATIO ...

jQuery function for shuffling the order of a random div?

Upon loading the page, I have implemented a code that randomizes the order of the child divs. Here is the code snippet: function reorder() { var grp = $("#team-posts").children(); var cnt = grp.length; var temp, x; for (var i = 0; i < cnt; ...

Creating Dynamic Visibility in ASP.NET Server Controls: Displaying or hiding a textbox based on a dropdown selection

Is there a way to dynamically show/hide a textbox or an entire div section based on a user's selection from a dropdown menu? Can this be achieved using client-side HTML controls instead of server controls? Would utilizing jQuery provide the best solut ...

Is it necessary to add a line break after a span element generated by react, next, or bootstrap

There is a strange issue plaguing my code - I'm enclosing some text in a span tag and it's causing an unexpected line break. It's unclear whether React.js, Next.js, or Bootstrap is the culprit, but I can't seem to get rid of the pesky l ...

The rule "react/jsx-sort-props" does not have a valid configuration

I've been attempting to organize props names alphabetically using the eslint-plugin-react plugin but I keep encountering this error: [Error ] .eslintrc.json: Configuration for rule "react/jsx-sort-props" is invalid: Value {"callbacksLast":true,"shorth ...

Drag and Drop in HTML5: Resize Div Automatically upon Transfer

I have implemented a drag and drop feature that transfers images into three different divs. However, I am facing an issue where the dimensions of the div do not adjust according to the image inserted, causing them to not fit in a single box. Additionally, ...