Luiz Felipe Felicio
Luiz Felipe Felicio

Reputation: 61

MUI v5 - Add component name to `styled` class names?

I did some search in github and here, but maybe I'm doing it the wrong way.

Using styled from @mui/material/styles generates random class names like this:

enter image description here

const TitleWrapper = styled('div')`
  display: flex;
  justify-content: space-between;
  margin-bottom: 2rem;
`

Sometimes it becomes hard to debug the app when we don't know where the rendered component came from.

There's an option parameter that can be passed to styled with a label prop that adds a suffix to the class:

enter image description here

const TitleWrapper = styled('div', { label: 'TitleWrapper' })`
  display: flex;
  justify-content: space-between;
  margin-bottom: 2rem;
`

Is there an automated way of adding that suffix to identify the component? It's really painful to do this in every single component.

Upvotes: 6

Views: 1463

Answers (2)

vbotio
vbotio

Reputation: 1674

The solution I found was to update my babel.config.js file with the following changes

plugins: [
  [
    '@emotion',
    {
      autoLabel: 'always',
      importMap: {
        '@mui/material': {
          styled: {
            canonicalImport: ['@emotion/styled', 'default'],
            styledBaseImport: ['@mui/material', 'styled'],
          },
        },
      },
    },
  ],
  '@babel/plugin-transform-runtime',
],

I hope this is useful to someone who faces the same issue.

Upvotes: 1

Shadi Amr
Shadi Amr

Reputation: 510

In order to get a custom class name i would like to suggest you to use scss (your own custom classes and styles), then you can put every style you need there , actually that's what i am doing right now, except when i need some styles based on some dynamic data then i can use both: my custom scss classes and styled-component class

Upvotes: 0

Related Questions