How to apply styles to a child component using CSS modules in a parent component

For the styling of a Material UI component (Paper) within a Menu component, I am referencing this documentation.

To style my components using CSS modules with Webpack as the bundler, here's an example:

// menu.js

import React from 'react';
import { StyledEngineProvider } from '@mui/material/styles';
...
import styles from './styles.module.css';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';


const MyMenu = (props) => {
  ...
  return (
    <StyledEngineProvider injectFirst>
      <div id="my-menu">
        <Button id="button-react-component" onClick={handleClick}>
          My Menu
        </Button>
        <Menu
          id="menu-react-component"
          ...
          className={styles.menu}
        >
          <MenuItem ...>
            <span> Example 1 <span>
          </MenuItem>
        </Menu>
      </div>
  );
}

// styles.module.css


.menu {
  color: white;
}

.menu .MuiPaper-root {
  background-color: red
}

// Also tried : 
.menu .root {
  background-color: red
}

The objective is to apply a specific background-color to the MuiPaper component. MuiPaper is nested within the Menu component, and its styling is defined through the parent declaration.<Menu>.

I prefer utilizing .css files for styling purposes and utilize webpack to bundle these css files into modules.

Observations in the browser : https://i.sstatic.net/Dja6H.png

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

It can be seen that the background-color "red" is not reflecting in the last screenshot.

Appreciate your assistance :)

Answer №1

To prevent CSS modules from overriding styles from another CSS module or elsewhere, there are a couple of workarounds you can use:

  1. Create a separate class specifically for the .menu paper, such as .menuPaper, and apply it using PaperProps on the Menu component:
.menuPaper {
  background-color: blue;
}
<Menu
  id="menu-react-component"
  ...
  className={styles.menu}
  PaperProps={{ className: styles.menuPaper }}
>
  1. Use the :global selector in your CSS selector:
.menu :global .MuiPaper-root {   
    background-color: red; 
}

CSS modules modify CSS classes by appending a unique ID to them. By using the :global selector, you can bypass this behavior and retain the original classname.

The difference between these methods is that when multiple Menu components are present in your MyMenu component, the :global approach would apply the same background to all Menu instances within MyMenu. Conversely, the PaperProps method would only style specific Menus with

PaperProps={{ className: styles.menuPaper }}
.

For more information, refer to the css-loader documentation: https://github.com/webpack-contrib/css-loader#scope

Explore MUI's Menu documentation here: https://mui.com/api/menu/#props (also check out the Popover component).

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

What is the best way to avoid having identical entries in a row when using jQuery's multiple select feature?

I am facing the challenge of working with multiple rows containing select boxes that have similar content. Each row has several select boxes and each item in a row can only be used once due to specific classifications assigned to each column. I want the se ...

Is there a specific requirement for importing a React component into a particular file?

I am facing an issue with my component and two JavaScript files: index.js and App.js. When I import the component into index.js, it displays correctly on the screen. However, when I import it into App.js, nothing appears on the screen. Here is the code fr ...

What is the most effective method for implementing a background repeated image in Foundation 4 framework?

Currently, I am utilizing the foundation4 framework for my website. In order to achieve a repeating tiled background, I have crafted a custom CSS file and included the following code snippet: body { background: url(img/floorboardsbg.jpg) repeat; } Whi ...

What is the best way to include an Interval in a button element?

I am currently working on developing an application that will automatically take a picture every minute using the camera. I want to implement a button tag with an interval so that when the application is running, it will capture an image every minute. i ...

Tips for avoiding background color interference with raycaster

In my current three js scene, I have a ground, sky, and various objects. I want specific objects to change color to red when the mouse hovers over them, but not all objects should do this. Currently, everything I touch turns red, which is not what I want. ...

Passing data into a different controller

In the process of building a system that involves selecting elements from a list and viewing their details, I have encountered an issue while using MEAN stack. My goal is to pass the id of the selected element to the controller of the second page. However, ...

Using Regex with JavaScript while ignoring letter case

I am trying to extract a query string from my URL using JavaScript, and I need to perform a case-insensitive comparison for the query string name. In order to achieve this, here is the code snippet that I am currently using: var results = new RegExp(&apos ...

React Component Functions for Export and Import

Currently working on a webapp built with React. My main component is defined in App.js, while I have another subcomponent responsible for creating buttons, like the logout button generated by renderLogoutButton(). But now, I want to reuse this function in ...

pm2 initiates two identical processes using distinct versions

I am currently using pm2 version 4.2.3 Upon executing the command: pm2 start node launchers/engine_launcher.js --name "engine", it initiates the following processes: id │ name │ namespace │ version │ mode │ pid - ...

Using JQuery to target the input value based on its ID

When trying to extract the value of the input with id "registration_type," I entered the following command in the console: $('#registration_type') The output displayed was: <input id=​"registration_type" name=​"contact_registration[ty ...

Iterate through a nested array in JavaScript and extract specific properties by comparing them to another array

Within my code, there is a kids object structured as follows: const kids = { name: 'john', extra: { city: 'London', hobbies: [ { id: 'football', team: &apos ...

Leveraging webpack alongside url-loader for embedding images within React applications

When styling with an inline style and passing in the URL of an image file, I typically do it as shown below: let url = `url(${this.state.logo})` var cardStyle = { backgroundImage: url, backgroundSize: '200px 50px' ...

The counterpart of the RxJS setTimeout operator

Looking for a RxJS operator alternative to set/clearTimeout in these circumstances: this.mouseEnterSubscription = this.mouseEnterStream .subscribe(() => { this.timeout = setTimeout(() => { void this.playVideo(); }, 500) }); this.mo ...

"Unlocking the hidden powers within a directive: A guide to accessing inner

I have two directives called container and item. directive('container', function(){ return { replace: true, template: "<div>contains <p>...</p> </div>' } }); directive('item', fun ...

Issue with passing props from parent component to child component in Vue.js not functioning

As a newcomer, I have been assigned a project that involves using Vuejs. In this project, there is a page that utilizes a component called DashboardCard. Each DashboardCard receives 2 props - val and icon from the parent component. https://i.stack.imgur. ...

Selecting the initial and final elements in a list without utilizing pseudo-classes

Currently, I am in the process of designing a custom MUI styled component and I have encountered a challenge. I want to apply extra styles specifically for the first and last child elements. The issue arises because MUI utilizes the emotion styled library, ...

Having trouble displaying nested JSON data in a DataTable

Hey, I've got a complex JSON array that's pretty nested and minified: { "items" : [ { "track" : { "album" : { "name" : "Pressure Makes Diamonds" }, "arti ...

Issue with displaying YouTube videos in HTML causing them to be downloaded instead of playing

I'm currently facing an issue with loading a video on my HTML page using the following code: <video v-for="(data, key) in projectData.videos" :key="key" width="320" height="240" controls> <source :src="data.url"> </video> One ...

Vue.js transition-group does not apply the *-move class

As I dive into learning Vue, I find myself wondering if I may have overlooked something fundamental or stumbled upon a bug. Despite multiple readings of the documentation at https://v2.vuejs.org/v2/guide/transitions.html#List-Move-Transitions, I still can& ...

Node js server for world's warm greetings

I have been attempting to utilize Node.js for hosting a web server on a dedicated PC, but unfortunately I am unable to access it from anywhere outside of my local network. After researching online, the general consensus is that all I need to do is enter t ...