2
votes

I have this JSX layout currently

<div className={classes.bottomArea}>
    <Box display="flex" flexDirection="column">
        <Typography variant="h1" component="span">1982</Typography>
        <Typography variant="h5" component="span">Bed Count</Typography>
    </Box>
</div>

And in my styles I'm trying to change the color of the h5 Typography element

bottomArea: {
    $h5: {
        color: "red"
    }
}

I think I understand why this isn't working but is there an easy way to target that h5 variant?

Here is a codesandbox to show

https://codesandbox.io/s/material-demo-wb7ts

3

3 Answers

1
votes

Assuming that you want to retain <span> as your component, you can target the h5 variant by targeting the CSS class added by Typography which is MuiTypography-h5.

In the syntax shown below, the & refers to the class generated for bottomArea and then the space indicates targeting .MuiTypography-h5 as a descendant.

import React from "react";
import Typography from "@material-ui/core/Typography";
import Box from "@material-ui/core/Box";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  bottomArea: {
    "& .MuiTypography-h5": {
      color: "red"
    }
  }
});

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

  return (
    <div className={classes.bottomArea}>
      <Box display="flex" flexDirection="column">
        <Typography variant="h1" component="span">
          1982
        </Typography>
        <Typography variant="h5" component="span">
          Bed Count
        </Typography>
      </Box>
    </div>
  );
}

Edit Target nested typography by variant

JSS Documentation: https://cssinjs.org/jss-plugin-nested/?v=v10.3.0#use--to-reference-selector-of-the-parent-rule

Related answer: How do you change a style of a child when hovering over a parent using material-ui jss styles

0
votes

You are using the Typography props the wrong way. The variant props only defines the style applied to the component whereas the component props defines which tag will be used to render this component.

If you want your Typography component to be a h5:

<Typography variant="h5" component="h5">Bed Count</Typography>

And then for the styling:

bottomArea: {
    '& h5': {
        color: "red"
    }
}

CodeSanbox: https://codesandbox.io/s/material-demo-6i1lq?file=/demo.js

Great day !

0
votes

you can use withStyle to update the specific component classes

check this Typography API

const Typography = withStyles(() => ({
  h5: {
    color: "red",
  },
}))(MuiTypography);

export default function Types() {
  return (
    <div>
      <Box display="flex" flexDirection="column">
        <Typography variant="h1" component="span">
          1982
        </Typography>
        <Typography variant="h5" component="span">
          Bed Count
        </Typography>
      </Box>
    </div>
  );
}

Edit Material demo