Search code examples
reactjsmaterial-uimedia-queries

How to use Media queries with Material UI makestyles


I'm pretty bad a CSS/styling and would appreciate some help here

I was trying to change the height of certain cards based on the screen width. using

let mainContainerHeight = window.innerWidth < 750 ? "50vh" : "80vh"

and assigning it to the height attribute, but it only applies when I refresh the page and not as a resize it.

I tried googling media queries and material UI but it looks completely different and tbh confusing...

https://material-ui.com/components/use-media-query/

Is there an easy way to just inject media queries into my code below??

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';

let mainContainerHeight = window.innerWidth < 750 ? "50vh" : "80vh"


const useStyles = makeStyles({
  root: {
    minWidth: 275,
    border: "3px solid black",
    borderRadius:"5px",
    boxShadow: "10px 5px 5px red",
    padding: 0,
    height: mainContainerHeight,
    overflow:"scroll"
  },
  small:{
    border: "5px solid black",
    borderRadius:"5px",
    boxShadow: "10px 5px 5px grey",
    marginBottom:"5px",
    marginTop:"8px",
    padding:"0px"
  },
  nomination:{
    border: "3px solid black",
    borderRadius:"5px",
    boxShadow: "10px 5px 5px red",
    padding: 0,
    height:mainContainerHeight,
    overflow:"scroll"
  },
  noPadding:{
    padding:"0px !important",
  }
});

export default function SimpleCard(props) {
  const classes = useStyles();
  const style = props.small ? classes.small : props.nomination ? classes.nomination : classes.root
  const padding = props.noPadding ? classes.noPadding : ""

  return (
    <Card className={style}>
      <CardContent className={padding}>
       {props.children}
      </CardContent>
    </Card>
  );
}

Solution

  • You could use 50vh as your default height and then use theme.breakpoints.up(750) to change it to 80vh.

    const useStyles = makeStyles((theme) => {
      return {
        root: {
          minWidth: 275,
          border: "3px solid black",
          borderRadius: "5px",
          boxShadow: "10px 5px 5px red",
          padding: 0,
          height: "50vh",                    // primary height
          overflow: "scroll",
          [theme.breakpoints.up(750)]: {
            height: "80vh"                   // secondary
          }
        },
        ...
      };
    });
    

    Edit aged-dust-tc6m5