Search code examples
cssmedia-queriesmaterial-uicreate-react-app

Access MaterialUI breakpoints inside css


Within a create-react-app project I'm using material-ui 1.x and creating a custom theme with custom breakpoints, as such..

import {  createMuiTheme } from '@material-ui/core/styles';
let customTheme = createMuiTheme({
  breakpoints:{
    values:{
      xs: 0,
      sm: 600,
      md: 960,
      lg: 1280,
      xl: 1920
    }
  }
});
export default customTheme;

Is it possible to reference those breakpoints inside a .css file. For example, I have a layout component that uses media queries...

...
@media screen
 and (max-width: 850px) and (min-width: 640px){  /* <--- HERE   */
    .layout-content {
        grid-template-columns: 1fr 200px 200px 200px 1fr;
        grid-template-rows: 64px 
                        auto
                        1fr
                        auto;
        grid-template-areas: "h h h h h"
                             ". l m m ."
                             ". r m m ."
                             "f f f f f";
    }
}
...

Is it possible to get the values for those css media queries from the materail-ui theme object?


Solution

  • OK. This led to a bit of a deep dive on my part. The react material-ui (https://material-ui.com) embraces CSS-in-JS so if you are choosing to work with this framework it really makes sense to go that route, which means converting my CSS to JSS and then accessing the material-ui theme object to get the media break points. That same bit of CSS now looks like this

     [theme.breakpoints.only('sm')]:{
        layoutContent: {
          gridTemplateColumns: '1fr 200px 200px 200px 1fr',
          gridTemplateRows:`64px
                            auto
                            1fr
                            auto`,
          gridTemplateAreas: `"h h h h h"
                              ". l m m ."
                              ". r m m ."
                              "f f f f f"`,
        }
      },
    

    Note, this is now JSON and not CSS.