Material-UiのDrawerで背景色を指定する

Material-UiのDrawerで飛び出てくるメニューの背景色を変更する方法です。

簡単かと思ったけど、意外とハマりました。

SwipeableDrawerでも同じ方法で変更できます。

サンプルコード

まずはmakeStylesをimportして、stylesを作成します。

import { makeStyles } from '@material-ui/styles';

const styles = {
  paper: {
    backgroundColor: 'red !important',  // !importantが重要
  }
}
const useStyles = makeStyles(styles);

次に作成したスタイルをDrawer(SwipeableDrawer)に渡します。

const classes = useStyles();
return(
  <SwipeableDrawer
    anchor={'left'}
    open={menuState['left']}
    onClose={toggleDrawer('left', false)}
    classes={{ paper: classes.paper }}  // styleを渡す
  >{getMenu('left')}</SwipeableDrawer>
)

注意点

background-colorを定義するときに「!important」をつけないと、どこかしらの何かしらのstyleに上書きされて反映されません。

const styles = {
  paper: {
    backgroundColor: 'red !important',  // !importantが重要
  }
}
関連記事
最新記事