LoginSignup
0
2

More than 3 years have passed since last update.

Material-UIのBadgeにスタイルを適用する方法

Posted at

日本語情報が見つからなかったため(※1)備忘録として残しておきます。

※1: Material-UIの公式ドキュメントの日本語訳におそらく存在するが、わしゃーわからん

状況

ページ上部のツールバーをデフォルトよりも狭くしているため、アイコン+バッジ表示をさせるとしっかりと収まりきらないのでなんかもやもやする

const useStyles = makeStyles((theme) => ({
  navbar: {
    height: 32,
    minHeight: 32,
  },
}))
  <AppBar position="static">
    <Toolbar className={style.navbar}>
      <IconButton aria-label="show 17 new notifications" color="inherit">
        <Badge badgeContent={17} color="secondary" >
          <Notifications fontSize="small" />
        </Badge>
      </IconButton>
    </Toolbar>
  </AppBar>

image.png

対応策

Badgeclasses{badge: style}の形でスタイルを渡してやるとうまくいくらしい

const useStyles = makeStyles((theme) => ({
  navbar: {
    height: 32,
    minHeight: 32,
  },
  badge: {
    height: 15, // デフォルトは20
    fontSize: '0.6rem' // デフォルトは0.75rem
  }
}))
  const style = useStyles();
  <AppBar position="static">
    <Toolbar className={style.navbar}>
      <IconButton aria-label="show 17 new notifications" color="inherit">
        <Badge badgeContent={17} color="secondary" classes={{badge: style.badge}} >
          <Notifications fontSize="small" />
        </Badge>
      </IconButton>
    </Toolbar>
  </AppBar>

image.png

結果

収まったけど文字が小さい

参考

How to style the badge component? - Stack Overflow

You can add styles to the inner span using the classes attribute:
<Badge badgeContent={"11"} classes={{badge: classes.myBadge}}>
Where myBadge is defined in makeStyles:
const useStyles = makeStyles((theme) => ({
myBadge:{
right: "inherit",
}
}));

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2