Issue with specific selectors causing React CSS module malfunction

Currently, I am a beginner in learning React and have been experimenting with CSS modules.

Even though Menu.module.css is mostly functioning correctly, it seems to be having an issue applying styles to the .menu a.last selector for some reason (although it works perfectly fine for .menu a). This problem persists when using CSS modules, but it functions as expected when using plain CSS.

Menu.jsx

import styles from './Menu.module.css'

export default function Menu({ className, items = [], children }) {
    return (
    <div className={`menu ${styles.menu} ${className || ''}`}>
      {children ? <h2>{children}</h2> : ''}
      <ul>
        {items.map((item, i) => (
          <li key={i}>
            <a
              href={item.href}
              className={item.className || ''}
            >
              {item.name}
            </a>
          </li>
        ))}
      </ul>
    </div>
  )
}

Menu.module.css

.menu a {
  color: black;
  text-decoration: none;
}

.menu a.last {
  background: red !important;
}

To view the code and HTML image, click here: https://ibb.co/r5m6W7s

I have attempted to access the a.last element through the console using the same querySelector as specified in the CSS file. It appears that this may indicate there is a logical issue or that CSS Modules selectors behave differently than regular CSS in this instance.

Although I believe this should be an easy problem to solve, I am currently unable to figure it out. Thank you for any assistance you can provide.

After switching back to plain CSS to verify if it would work, it did indeed work.

Despite starting from scratch with CSS Modules, the problem persisted when attempting to apply styles again.

As an additional test, I tried changing class names and even used a plain class name (not randomly generated by the CSS Modules compiler), but the issue remained unresolved while still working with the .module.css file.

Answer №1

My recommendation would be to utilize

className={styles[item.className] || ''}
.

item.className doesn't point to a CSS module.

Answer №2

Resolved by cheesyMan: I overlooked the fact that all class names in the CSS file had changed after using CSS modules. I only utilized the .menu CSS module selector without considering the .last CSS module selector/property. The code was written as .menu_random123 a.last (incorrect) when it should have been .menu_random123 a.last_random123. It was difficult to spot this mistake because the .last class was inherited from the parent element.

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 MongoDB's find() method returning incorrect objects?

My current task involves running a Mongo query on the Order database to retrieve orders associated with a specific user by using their email. This process is achieved through an API, but I'm encountering difficulties as the returned object contains un ...

Guide to Implementing a Single Trigger Click with jQuery for Window Scrolling

I have implemented JavaScript code for a button that loads additional posts from the database. The button has the class of .getmore. My goal now is to enable infinite scroll so that users do not have to manually click the button. In order to achieve this ...

Efficiently scheduling file downloads using WebDriver automation

I am in the process of automating a website using WebDriver, but I have encountered unique file download requirements that differ from what is readily available online. My specific scenario involves a website where I create orders. Upon clicking the &apos ...

Dynamic key flow type where all keys are of the same type

My Firebase database is organized in the following manner: user: { cart: { "randomid": quantity, "randomid": quantity } } I want to avoid hardcoding item ids into a flow type. Is there a way to define a type where every key is a number, simil ...

When the div is loaded, automatically navigate to the crucial li element within it, such as the one with the class "import

Welcome to my first webpage: <html> <head> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <div id="comment"></div> <script type="text/ja ...

What steps can be taken to fix the issue of "Module not found: Can't resolve 'firebase/storage' in next.js" even after adding firebase using yarn?

I am trying to integrate Firebase into my Next.js file, but I keep getting an error saying "module not found". Can someone help me apply Firebase in this file? import Image from 'next/image'; import { useSession } from 'next-auth/client&apos ...

Unable to get click function to work with multiple div elements

Using four div elements, I have implemented a feature where clicking on the first div causes all other div elements to change opacity. This is working correctly. However, I would like the opacity of the first div to remain unchanged when moving to another ...

The Next.js page suddenly disappears after a moment

Out of the blue, my next.js page suddenly went blank for no apparent reason. I didn't make any changes, it just happened. I attempted to restart my dev server and even deleted the '.next' folder, but nothing seemed to fix the issue. Despite ...

Creating an Editor for Input Text Field in HTML: A Step-by-Step Guide

In the vast landscape of JS libraries that can achieve this function, like Trumbowyg and more. However, prior to my rails project displaying that slim version, I need to ensure JavaScript is properly escaped! Therefore, I need to create an editor using o ...

Is there a way to prevent undefined properties when using .each in jQuery with a JSON object?

I am trying to populate the values of <inputs> on a webpage using data from a JSON object. http://codepen.io/jimmykup/pen/exAip?editors=101 To begin, I create a JSON object with two values - one for name and one for url. var jsonObj = []; var nam ...

Is there a single code that can transform all standard forms into AJAX forms effortlessly?

When manipulating my 'login' form, I love using this code to submit it to the specified url and display the response in the designated id. The method of submission is defined as well. It's a great solution, but is there a way to streamline ...

Instruction failed to produce HTML output

Currently facing a challenge with my code - I have a dynamically created span (via ng-repeat). <span my-size id="abc"></span> <span my-size id="def"></span> <span my-size id="ghi"></span> The goal is to extract the id ...

What is the best way to retrieve a default property from a JavaScript literal object?

In the following example, a JS object is created: var obj = { key1 : {on:'value1', off:'value2'}, key2 : {on:'value3', off:'value4'} } Is there a clever method to automatically retrieve the default valu ...

Steps for leveraging pdfMake with live data

Recently delving into Angular, I've been exploring the capabilities of pdfMake. While I successfully incorporated static data, I'm facing challenges when attempting to utilize dynamic data. Any guidance on how to achieve this would be greatly app ...

Limit the elements in an array within a specified range of dates

Currently, I am working on implementing a filter functionality for a data array used in a LineChart within my Angular application using TypeScript. The structure of the data array is as follows: var multi = [ { "name": "test1", "series": [ ...

How can I effectively structure swiper js props within a react application to ensure clean code?

I'm attempting to structure the code in a similar way, resembling framer motion variants: export default function Carousel() { const [index, setIndex] = useState(null); const swiper_varinats = { allowTouchMove: false, slidesPerView: 2, ...

Ways to align anchor tags in the middle of a DIV element?

<div style="border: 1px solid rgb(0, 0, 0); height: 30px; width: 30px; background-color: rgb(245, 225, 130);"> <div style="margin: 5px;"> <a href="#link">#down2#</a> </div> </div> This is the current code I am w ...

What could be causing my JavaScript function to produce repeated letters with just one key press?

After implementing a code that generates different variables based on the 'truth' variable, I encountered an issue. Everything works flawlessly when 'truth' is set to "name," but as soon as I switch it to "email," any keystroke results ...

Having trouble with adding Jquery UI CSS to my project even after bundling

I have implemented jQuery UI in my small project, but the CSS styles are not being applied. The following bundle includes the necessary CSS files: bundles.Add(new StyleBundle("~/Content/themes/base/css").Include( "~/Content/themes/base/jque ...

Shifting the MUI DataGrid Pagination table to the left with CustomPagination: A step-by-step guide

Hey everyone, I am currently diving into the MUI data grid to gain a better understanding. In order to meet my design requirements for a table view, I have incorporated the DataGrid component from MUI. For pagination, I am utilizing their custom implementa ...