Is it possible to use MaterialUI with React and css modules and access the theme inside the css module file?

Viewed 1755

I am using Material UI with a React application. For generic styles I just simply use global theme override. But there are some specific rules depending on the context, and for that I would like to use css modules. Is it possible to access the theme inside the css module?

I didn't find anything about this in the Material UI documentation. Also tried to google it, but too much people have an issue with the specificity problems when trying to override MaterialUI rules with CSS modules.

2 Answers

It is not possible.

Solved it by documenting the colors, fonts, spacing etc. in scss variables.

Still overriding the global theme, we can import the scss variables to access them.

When we have to use component specific styling we can still use scss modules and import the variables to access the theme.

So we use the scss variables as the single source of truth.

if you increase the specificity of your selectors, nest them, it should work...

// about.module.scss

.container {
  .button {
    background-color: green;
  }
}
about.jsx

import styles from './about.module.scss';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import Container from '@material-ui/core/Container';
import Copyright from '../src/Copyright';
import Link from '../src/Link';
import ProTip from '../src/ProTip';
import React from 'react';
import Typography from '@material-ui/core/Typography';

export default function About() {
  return (
    <Container maxWidth="sm" className={styles.container}>
      <Box my={4}>
        <Typography variant="h4" component="h1" gutterBottom>
          Next.js example
        </Typography>
        <Button variant="contained" color="primary" className={styles.button} component={Link} naked href="/">
          Go to the main page
        </Button>
        <ProTip />
        <Copyright />
      </Box>
    </Container>
  );
}

enter image description here

Related