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

Mastering the art of debugging a mongoose action in node.js

I am utilizing mongoose for connecting my node.js app with mongoDB. However, I am facing an issue where the database does not get updated when I create or update a model instance. How can I effectively debug and identify what goes wrong in the create or up ...

Is it possible to create a pure CSS responsive square that is positioned to the top right of a div element of any size?

My current goal is to achieve the following task... I aim to position a square perfectly in one or both corners of the top right section of a div, ensuring it never exceeds the boundaries regardless of the div's size or dimensions that necessitate th ...

Setting values and options in Material UI AutoComplete and then assigning the selected value to an object when onChange event occurs - how can it be

I am working on a project where I have a brand object with the field cat_id. When the page loads, categories are loaded into an autocomplete select. My goal now is to set the value of category id as the value for a category option in the autocomplete, an ...

Utilizing jQuery UI autocomplete with AJAX and JSON data sources

I've been facing an issue with the jQuery UI autocomplete feature, and despite extensive research, I have only managed to partially resolve it. The code below is what I'm currently using to make it work: $("#term").autocomplete({ source: fun ...

Changing the name of a React dropdown item when a selection is made

When using the handledealernameChange function in the code below, I am unable to pass {option.OrgName} as an argument. Could someone provide assistance in retrieving the text? I am new to this and would appreciate any help. return ( <Select className ...

Is there a performance benefit to using node.js over client-side JavaScript in comparison to Chrome/V8?

Currently, I am working on a client-side javascript application for image manipulation. However, some of the operations are running quite slowly in the browser, taking about 2-3 seconds to complete. To address this issue, I am considering implementing a s ...

The functionality of changing the category in the second carousel slider on click using JavaScript appears to

Creating a bootstrap carousel slider that dynamically changes based on the selected category. For example, clicking on the hammer category will display only hammer images, while selecting the compass category will show compass images. Everything worked sm ...

The getJSON API functions properly on a local machine but encounters issues when deployed on a

I have a vision to create a web application that can display the weather of any city based on user input. I've divided my project into three files - index.html for collecting user input, index2.html for retrieving and displaying the data, and a CSS fi ...

The not-found.js file in Next.js is displaying an empty page rather than showing a 404 error message

My current project involves using Next.js v13.4.19 with the app router mode. However, I seem to be facing an issue with the not-found.js page located in the app folder. Whenever a non-existing route is accessed, it does not render a 404 page as expected. ...

How to create a CSS animation that gradually darkens a background image during a

Currently in the process of constructing a page with an intriguing background image: body { background:url(images/bg.png) center center no-repeat fixed; -webkit-background-size:cover; -moz-background-size:cover; -o-background-size:cover; ...

Utilize vue.js to save the components of an object

data() { return: { user: {}, userName: "", userAge: "" } }, methods: { saveUserName: function() { this.userName = this.newUserName; this.$refs.userNameModal.hideModal(); this.$ ...

Tap and conceal feature on a mobile website

I seem to be facing a JavaScript challenge. On the desktop version of my website, I've managed to create a functionality where hovering over a button reveals some text, and clicking anywhere else on the site hides the text. However, I'm now stru ...

Invoking functions within a jQuery extension

I've come up with this code to define the instance of my plugin: $.fn.someplugin = function(opts) { $(document).on('click', '.option-1', function() { alert(1); }); }; To make my plugin work, I utilize code similar to this ...

Creating a Dynamic Navigation Bar with HTML and CSS

I've been exploring the code on w3schools.com, and while there are some great examples, I'm struggling to understand it all. Unfortunately, there aren't any instructions on customizing the code for a third level of menus. Can someone simplif ...

How can I center two images using a hover effect in WordPress?

When the mouse hovers over an image, it changes to another image. Everything works smoothly except for one issue - the image is not centered. Below is the code I am currently using: HTML: <figure> <a> <img class="hover" src="na ...

Minimize the use of globalized variables in your LESS CSS code

Is there a better way to avoid using globally diffused variables? I conducted a test with the following setup: _import.less @test: #FFF; _import2.less @test: #000; test.less @import (reference) "_import"; body { background: @test; } test2.less ...

What is the best way to save a large quantity of objects to a server using ajax and php?

Imagine a scenario where I have a page containing 100 objects, each around 700 bytes when converted to json format. When it comes to saving these objects to the php based controller, there are several options available to me. Option 1: For each object ( ...

Comparing parameters between two functions in Javascript: a step-by-step guide

I am currently working on solving this problem: var name; var totalScore; var gamesPlayed; var player; var score; // Creating the game player object function makeGamePlayer(name, totalScore, ga ...

Create a Vue component that utilizes the v-for directive to iterate through a list of items, passing data from a

Imagine having two arrays with a similar structure like this: const individuals = [{name: "Jane Doe", id: "0001"},{name: "John Doe", id:"0002"}, {name: "Sam Smith", id: "0003"}, {name: "Joe ...

What is the best way to pass a reference from one component to another component using a mapped list?

Here is an array of objects representing services: export const serviceList = [ { title: "Exterior Services", image: "/images/service-card-images/kendall-painting.webp", description: "ExteriorServicesDescription" ...