0
votes

I am using material UI for my project and I am sick of naming tone of className for each item of my component so I have a question like this:

import { makeStyles } from "@material-ui/core/styles";
import { Button } from "@material-ui/core";

const useStyles = makeStyles((theme) => ({
  container: {
    background: "pink"
  },
  item: {
    height: "200px",
    width: "200px",
    background: "lightblue",
    margin: "10px",
    "&:last-of-type": {
      background: "red"
    },
    h1: {
      color: "green"
    }
  }
}));

export default function container() {
  const classes = useStyles();

  return (
    <div className={classes.container}>
      <div className={classes.item}>
        <Button variant="contained" color="primary">
          Primary
        </Button>
      </div>
      <div className={classes.item}>
        <h1>Text in 2nd item</h1>
        <input type="text" />
      </div>
      <div className={classes.item}>
        <h1>Text in last item</h1>
        <Button variant="contained" color="primary">
          Primary
        </Button>
      </div>
    </div>
  );
}

enter image description here

As you can see in the code up here I have a container with a pink background contains 3 lightly blue background items:

The first item has a button import from '@material-ui/core', the second one contain a h1 text and an input and the last one has a h1 text and a button import from '@material-ui/core'.

I want to change color of h1 text in the second item by modifying className item ( please do not name any className in that h1 tag ) into yellow

and I want to change background color of Material Ui button in the last item only (the style of Material UI button from the first item is still remained) by overriding className .MuiButton-containedPrimary in className item as well

Feel free to change the code in this codesandbox link here. Thanks for your help, it means a lot to me, sincerely have a good day

1

1 Answers

0
votes

nested CSS selectors can be used in this case.

const useStyles = makeStyles((theme) => ({
  container: {
    background: "pink"
  },
  item: {
    height: "200px",
    width: "200px",
    background: "lightblue",
    margin: "10px",
    "&>h1":{
      color:'green'
    },
    "&>button:last-of-type": {
      background: "red"
    },
  }
}));

Here is the JSS documentation.

Here is the working demo:
Edit stackoverflow access style  (forked)