How to change font size of material ui badge content in reactjs?

Viewed 4919

I want to change the font size of the label in material ui badge. I am using style={{ fontSize: "15" }} but that only affect its child, which is an icon.

Code:

<Badge badgeContent={props.cartCount} color="secondary" style={{ fontSize: "15" }}>
    <ShoppingCart className={classes.mediumIcon} />
</Badge>
4 Answers

Ideal way would be use classes badge as mentioned in documentation

import { Badge } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import "./styles.css";

const useStyles = makeStyles((theme) => ({
  badge: {
    fontSize: 30
  }
}));

export default function App() {
  const classes = useStyles();
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Badge
        badgeContent={"h"}
        color="secondary"
        classes={{ badge: classes.badge }}
      />
    </div>
  );
}

You can modify the font-size as below. create styles of different font-size in useStyles

const useStyles = makeStyles((theme) => ({
  font1: {
    fontSize: "1rem"
  },
)}

And then assign it as below to the Badge component

<Badge
        classes={{
          badge: classes.font1
        }}
        badgeContent={99}
        {...defaultProps}
      />

Sandbox

If you use mui system then this can change badge font size

    <Badge
        badgeContent={9}
        color="error"
        overlap="circular"
        sx={{ "& .MuiBadge-badge": { fontSize: 9, height: 15, minWidth: 15 } }}
    >
        <IconButton sx={{ p: 0, color: "primary.main" }}>
            <Notifications />
        </IconButton>
    </Badge>

You can use the componentProps attribute as follows (this example changes the color of the text in the badge but the same principle will work for fontSize).

  <Badge badgeContent={comments}  componentsProps={{ root: {style: {color: 'white'}}  }}>
     <CommentIcon  />
  </Badge>
Related