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 :

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 ensure consistent spacing after dropping an element while using react-beautiful-dnd?

I'm currently integrating Material UI and react-beautiful-dnd to develop a basic column layout using Grid where elements can be rearranged. However, I've encountered an unusual spacing issue between the elements that's challenging to describ ...

Setting the initial value for React useState does not result in any changes

Here is the code snippet from my functional component that demonstrates the issue: Is there a way to set the initial value in useState() hook after some data processing? const data = props.data ? props.data : {}; const statusOptions = [ { label: "Activ ...

Seamless Integration of jQuery Functions

I am in need of some assistance with passing a chain of jQuery methods into a function as an argument. The goal is to have dynamic methods executed on a DOM object. This functionality would be particularly useful for writing qUnit tests where centralizat ...

Showing various information in tab form depending on a specified variable

In my current project, I am developing a user-friendly view that allows users to easily switch between different sets of data. The specific scenario involves a manager overseeing multiple stores with various franchises. Our dashboard presents aggregated re ...

Extracting Parameters using JQuery's load Method

On a webpage, I am attempting to load a jsp page (another.jsp) within a div element while passing parameters. $("#div").load('another.jsp?a=1&b=2'); Despite trying various methods multiple times, I have not been able to get the desired outc ...

Modifying the color of drawings on a Javascript canvas

I am currently working on developing a drawing board using HTML and JavaScript (Node.js on the server side). One challenge I'm facing is implementing a color picker that allows users to change the paint color dynamically. While I could hard code the c ...

The bottom margin of the last element does not affect the size of its container

I'm curious as to why the margin-bottom of .content-b isn't affecting the height of the .container. .container { background: grey; } .content-a, .content-b { height: 100px; border: 1px solid red; margin-bottom: 100px; } <div class= ...

Capture a snapshot of a webpage that includes an embedded iframe

Currently, we have a nodeJS/angular 4 website that contains an iframe from a third party (powerBI Emebdded). Our goal is to develop a feature that allows the end user to capture a screenshot of the entire page, including the content within the iframe. We ...

Remove focus from input field after submitting in a project using Typescript and React with react-hook-form

I'm currently working on a TS-React project and encountering an issue with barcode scanning in my inputs. I am using react-hook-form along with the useForm Hook. The form consists of one input-text field and a submit button, both within a global form. ...

Make the textarea larger and bring it to the forefront when it is selected

I would like to make a textarea expand (increase its height) when it is in focus. The expanded textarea should not push the content down, but rather be displayed above other content. Currently, this is the code I am using (check out the example here): $( ...

Understanding the user's preference for text alignment and managing how the text is displayed in a text area (or text field) within a ReactJS application

My latest project is an app that features multiple text areas. Personally, I use the app with two languages - English and another language that is aligned to the right. However, the default setting has the text-areas aligning to the left. To change this ...

Implement real-time updates on the React frontend application by utilizing the state hook in React.js to dynamically

While I was making changes to my code in order to ensure that the update request works smoothly without refreshing the react frontend, things didn't go according to plan. Here's where I currently stand: On the "Profile" component page, I created ...

What is the best way to show distinct items and their frequencies from an array of objects in Vue.js/JavaScript?

I have been developing an inventory management application using Vuejs, and I am facing a JavaScript-related challenge in my project. The issue revolves around handling data that includes user information retrieved from a form, as well as static categories ...

Having trouble with JQuery's .prop function not unchecking a checkbox?

I have been experimenting with different solutions in order to uncheck a checkbox when another checkbox is checked. Unfortunately, none of the methods I've tried seem to be working effectively... Currently, my code looks like this: $("#chkBox1").cli ...

What is the best way to handle the keystroke event in a $.bind method?

I'm struggling with passing a specific keystroke through the bind method. $(document).bind('keyup', event, keyup_handler(event)); This is my attempt at solving it.. Here is the function it should be passed to: var keyup_handler = functio ...

What are the best ways to position elements within a div?

In my small information div, I am looking to align the content on the right side. Specifically, 065 31 323 323, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5d4c4c1c0cbdfc4e5c2c8c4ccc98bc6cac8">[email protected]</ ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Exploring ways to target a child div within props such as avatar and actions of cardHeader (a child of the card element from MaterialUI) using Jest and En

Currently, I am in the process of creating test cases for a React.js class using Jest and Enzyme frameworks. The class utilizes the Card component from Material UI, and a snippet of my code is shown below: <Card> <CardHeader avatar = ...

*NgFor toggle visibility of specific item

Here is a snippet of HTML code that I'm working with: <!-- Toggle show hide --> <ng-container *ngFor="let plateValue of plateValues; let i=index"> <button (click)="toggle(plateValue)">{{i}}. {{ btnText }}</button> ...

How can I use AJAX to automatically populate a dropdown menu with cities in a PHP MVC application?

Within a PHP MVC setup, there is a file named city.php in the model section which defines a city class. The city class contains a method called getCitiesByProvince('ProvinceId') that retrieves all cities for a given province. When a user picks ...