Is it possible to configure mui v5 to display class names without the css-xxx prefix?

Working with mui has truly been a delightful experience. Each developer seems to have their own unique approach when it comes to styling and layout in react. The flexibility provided by mui must present quite the challenge for library developers.

In customizing mui, I decided to focus on working with the global theme. This involved creating specific class names to apply to elements like MuiContainer. Initially, I relied on selectors within the overrides, but now mui offers component-specific styleOverrides prop.

Unfortunately, my selectors are not functioning properly due to the following change:

// Class names in v4
.MuiContainer-root

// Class names in v5
.css-1oqqzyl-MuiContainer-root

I'm left wondering if there is a way to ensure uniform rendering of class names by the theme engine. Could this shift be indicative of mui's reliance on emotion?

On a side note, when viewing the rendered output in v4, the class names included my custom classes as well:

.MuiContainer-root.Luci-AppLayout.root

An additional observation in v5 reveals that each element now possesses three sets of class names:

  • mui without prefix
  • mui with prefix (absent in v4)
  • my custom classes remain untouched

Interestingly, only the mui class names with prefix show up in the inspection window, indicating which classes are actually being used to style the element.

Addendum

As per feedback from @Ryan Cogswell, both versions of class names are present in the html. However, during inspection using dev-tools, only the prefixed class names are utilized to style the elements.

To replicate the issue, please refer to the sandbox link below and inspect the code in the dev-tools:

https://codesandbox.io/embed/sad-varahamihira-pv73t5?fontsize=14&hidenavigation=1&theme=dark

Here's the code snippet from the sandbox example:

import Button from "@mui/material/Button";
import "./styles.css";
import { createTheme } from "@mui/material/styles";
import { ThemeProvider } from "@mui/styles";

const theme = createTheme({
  components: {
    // Component name
    MuiButton: {
      styleOverrides: {
        // Slot name
        root: {
          // CSS styling
          color: "red",
          "&.Custom": {
            color: "green"
          }
        }
      }
    }
  }
});

export default function App() {
  return (
    <ThemeProvider theme={theme}>
      <div>
        <h1>Hello CodeSandbox</h1>
        <Button className="Custom">Testing</Button>
      </div>
    </ThemeProvider>
  );
}

Answer №1

We identified two issues with the code in your sandbox.

  1. The theme had a typo where it was using ccomponents instead of components. This seems to be a specific typo in your sandbox and not present in your actual codebase.
  2. You were importing the ThemeProvider from "@mui/styles" instead of "@mui/material/styles". The former is for the legacy JSS styling approach, while the latter integrates with the "@mui/material" styling engine and makes the theme visible to it.

A corrected version of your sandbox code is provided below:

import Button from "@mui/material/Button";
import { createTheme } from "@mui/material/styles";
import { ThemeProvider } from "@mui/material/styles";

const theme = createTheme({
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          color: "red",
          "&.Custom": {
            color: "green"
          }
        }
      }
    }
  }
});

export default function App() {
  return (
    <ThemeProvider theme={theme}>
      <div>
        <h1>Hello CodeSandbox</h1>
        <Button className="Custom">Testing</Button>
      </div>
    </ThemeProvider>
  );
}

https://codesandbox.io/s/condescending-dew-r1kwc1?fontsize=14&hidenavigation=1&theme=dark

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

Tips for customizing an image within the antd upload component

Using the upload feature within an antd form component has presented me with a challenge. <Form name="posting" onFinish={onSubmitForm} scrollToFirstError encType='multipart/form-data' > <Form.Item name=&qu ...

Extracting JSON data from Stripe results - A comprehensive guide

I'm having trouble displaying the 'amount_total' in an h1 tag from my Stripe JSON response. Every time I try, I encounter this error: TypeError: Cannot read property 'map' of undefined Here is a snippet of the Stripe JSON output: ...

Material-UI Slide component is encountering an issue where it is unable to access the style property of an undefined variable

Recently, I incorporated Material-UI Slide into my project and I'm curious about why the code functions correctly when written in this manner: {selectedItem && selectedItem.modal && selectedItem.modal.body ? ( selectedItem.modal.body.map((section ...

What is the best way to create a reusable component for a dialog box or modal window?

I have been working on developing a reusable dialog component with a yes or no button at the bottom. The main idea behind this is to create a user confirmation dialog that prompts the user to confirm their entered information before proceeding. import Re ...

My element is unexpectedly changing its properties

One puzzling issue I'm facing involves a component that retrieves an array from a parent prop, stores it in a state, makes modifications to the array, and then aims to send the modified version back up to the parent. The confusion arises when I obser ...

Material UI checkbox claims to be uncontrolled

Currently, I am utilizing the Material UI kit for React to create dynamic Checkboxes by updating them from states. However, an error message stating "uncontrolled element" keeps appearing. this.state = { items : [{item: "item1", checked: false}, ...

Creating a dynamic mouse trail effect using CSS and JavaScript without compromising element clickability

I'm looking to create a mouse trail that follows the cursor as it moves, made up of small icons or images that gradually fade out over time. I attempted to achieve this by overlaying a grid on top of all other elements on the page. The grid consists o ...

Utilizing jQuery for easy drag-and-drop functionality in web development

I have two lists which are currently using jQuery for functionality. An example can be found here. I need the same basic functionality but with some modifications: Instead of just getting all sortable items by clicking "Get items," I want to be able to dr ...

Encountering a problem in a NextJS application where an error occurs stating "cannot read property of undefined (reading setState)" within

In an attempt to resolve the issue, I have linked the method to this inside the constructor. Additionally, I have utilized the arrow function technique to address the problem at hand. Despite these efforts, I continue to encounter the following error: Unha ...

What are the steps to enable CSS code completion for JavaFX again?

Hello everyone, Recently, I disabled the CSS code completion feature for JavaFX-Tags such as '-fx-...'. Unfortunately, I'm not sure how or why it happened but now I would like to enable the code suggestions again. I have been unable to loca ...

The perpetual loop in React context triggered by a setState function within a useEffect block

I'm experiencing an endless loop issue with this context component once I uncomment a specific line. Even after completely isolating the component, the problem persists. This peculiar behavior only manifests when the row is discounted and the browser ...

Vite build error: TypeError - Unable to access properties of null while trying to read 'useContext'

I used the following component imported from material-ui : import Paper from '@mui/material/Paper'; After running npm run build followed by npm run preview, I encountered an error in the console: Uncaught TypeError: Cannot read properties of n ...

Stop Bootstrap IE menu from closing when scrollbar is clicked

When using IE, the dropdown menu closes when clicking on the scrollbar. However, it functions properly when scrolling with the mouse wheel. To see the issue in action and potentially offer a solution, you can visit this Codeply link: I'm seeking sug ...

How can I use React to switch the visibility of a nested component from the parent container component?

Objective I am in the process of replicating a List Control Component using React and Redux, following the guidelines outlined in Google Material Design layout. This list control will enable users to create, rename, and delete items within the list witho ...

React.js and Visual Studio Code have recently been causing unexpected and massive "Module not found" errors

Everything was going smoothly with my project until I uploaded it to Github and then cloned it. Suddenly, I started encountering various "Module not found: Can't resolve..." import errors. For example: Module not found: Can't resolve './co ...

Is using display:table an effective approach for achieving equal height columns?

I am currently working on a responsive design project and I need two columns of equal height. I do not want to rely on JavaScript for this, and I prefer having some whitespace between the columns to enhance readability. I have tried two different layouts; ...

What is the best way to update a value and trigger a re-render in ReactJS?

this.state={ value: 'v1', newValue: '', } componentDidMount = () => { let nV = this.state.value + 'received'; this.setState({ newValue: nV, }); } tabClick = (val) => { this.setState({ value: val, ...

Creating a Select component in React without relying on the Material-UI library involves customizing a dropdown

Is there a way to achieve a material UI style Select component without using the material UI library in my project? I'm interested in moving the label to the top left corner when the Select is focused. export default function App({...props}) { retu ...

centering the text within the div for perfect alignment

I've been attempting to customize a Register form. My goal is to position the heading in the center of the div while having another login form located right beside it. Using flexbox, I styled them and then applied justify-content as center. Additiona ...

How can we use Jquery to add animation effects to our styling

I am a beginner with JQuery and struggling to make the code below work correctly. $('.announcement_panel_button').click(function(e){ $('#site_logo').animate({ 'margin-top': '5px' }, 5000); e.pre ...