はじめに
MaterialUIを使っていて、スタイル調整したい時にmakeStylesを使うことがあると思います。
breakpointsやpaleteなどのthemeを使おうと思ったときに、defaultTheme型にはbreakpointsがないとTypeScriptのコンパイルエラーが出たので調べたら、makeStyles自体が@material-ui/core/stylesと@material-ui/stylesの二つからインポートできるんですね。
で、どう違うのか調べたので書いておきます。
ちなみにVSCodeの補完機能で、インポートした場合に@material-ui/stylesからインポートされてしまってエラーがでたので気づきました。
公式ページ
調べてみると@material-ui/core/styles vs @material-ui/stylesという項目に以下のように記載されていました。
Material-UIの使用時にインストールするパッケージの数を減らし、インポートを簡略化するために、
@material-ui/stylesモジュールは@material-ui/core/stylesから再エクスポートされます。
// Re-export with a default theme
import { makeStyles } from '@material-ui/core/styles';
// Original module with no default theme
import { makeStyles } from '@material-ui/styles';
とりあえずデフォルトのテーマを使いたい場合は、@material-ui/core/stylesからインポートして、使わない場合は'@material-ui/styles'からインポートすれば問題なさそうです。
Theme型について
@material-ui/core/stylesからインポートすればmakeStylesに渡すコールバック関数の引数に受け取るthemeがTheme型になります。ですので、breakpointsやpaletteが使えます。
import { makeStyles } from "@material-ui/core/styles";
// themeがTheme型に推論されるのでbreakpointsが使える
const useStyles = makeStyles((theme) => ({
drawer: {
[theme.breakpoints.up("sm")]: {
flexShrink: 0,
width: 256,
},
},
}));
以下のようにThemeもインポートして、themeに型付けしてあげてもいいと思います。
import { makeStyles, Theme } from "@material-ui/core/styles";
const useStyles = makeStyles((theme: Theme) => ({
//省略
}));
ちなみにTheme型は以下のように定義されています。
export interface Theme {
shape: Shape;
breakpoints: Breakpoints;
direction: Direction;
mixins: Mixins;
overrides?: Overrides;
palette: Palette;
props?: ComponentsProps;
shadows: Shadows;
spacing: Spacing;
transitions: Transitions;
typography: Typography;
zIndex: ZIndex;
unstable_strictMode?: boolean;
}
DefaultTheme型について
@material-ui/stylesからインポートすると、Theme型がないのでDefaultTheme型になります。
import { makeStyles } from "@material-ui/styles";
// themeがDefaultTheme型に推論されるのでbreakpointsが使えない
const useStyles = makeStyles((theme) => ({
drawer: {
[theme.breakpoints.up("sm")]: { // エラー!!
flexShrink: 0,
width: 256,
},
},
}));
DefaultTheme型は次のようにテーマの中身が記載されていないため、breakpointsなどは使えません。
export interface DefaultTheme {}
まとめ
自分はデザインセンスが皆無で、社内の業務システムとか作る時にMaterial-UIがものすごく便利なので重宝しています。同じような方は是非使ってみてください。
あと、TypeScriptで書けばコード作成中にチェックできるので、やっぱりTypeScriptは学ぶべき言語だと思いました。
間違ってたら指摘していただけると幸いです。