React + Material-UIで手っ取り早くBottomNavigationの色を変えようと思ったのですが、ハマったのでメモ。
最終的なコードはこんな感じ。
Footer.tsx
import React from "react";
import makeStyles from "@material-ui/core/styles/makeStyles";
import createStyles from "@material-ui/core/styles/createStyles";
import { Theme } from "@material-ui/core/styles";
import BottomNavigation from "@material-ui/core/BottomNavigation";
import BottomNavigationAction from "@material-ui/core/BottomNavigationAction";
import RestoreIcon from "@material-ui/icons/Restore";
import FavoriteIcon from "@material-ui/icons/Favorite";
import LocationOnIcon from "@material-ui/icons/LocationOn";
import AppBar from "@material-ui/core/AppBar";
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
width: "100%",
backgroundColor: theme.palette.primary.main,
},
appBar: {
top: "auto",
bottom: 0,
},
})
);
const actionStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
backgroundColor: "inherited",
"&$selected": {
color: theme.palette.secondary.main,
},
},
selected: {},
})
);
export default function Footer() {
const classes = useStyles();
const actionClass = actionStyles();
const [value, setValue] = React.useState(0);
return (
<AppBar position='fixed' color='primary' className={classes.appBar}>
<BottomNavigation
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
showLabels
classes={{ root: classes.root }}
>
<BottomNavigationAction
classes={actionClass}
label='Recents'
icon={<RestoreIcon />}
/>
<BottomNavigationAction
classes={actionClass}
label='Favorites'
icon={<FavoriteIcon />}
/>
<BottomNavigationAction
classes={actionClass}
label='Nearby'
icon={<LocationOnIcon />}
/>
</BottomNavigation>
</AppBar>
);
}
Material-UIの"Overriding styles with classes"を使っています。
https://material-ui.com/customization/components/#overriding-styles-with-classes
makeStylesでスタイルを作ります。
BottomNaviationActionのstyle.tsx
const actionStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
backgroundColor: "inherited",
"&$selected": {
color: theme.palette.secondary.main,
},
},
selected: {},
})
);
classesの引数でこのスタイルをとります。
.tsx
const actionClass = actionStyles();
<BottomNavigationAction
classes={actionClass}
label='Nearby'
icon={<LocationOnIcon />}
/>
これだけといえばこれだけですが、洗濯した後の色の指定に意外とハマりました。
selected: {} のところは必須です。(オリジナルのクラスを消さないと反映されない)