🔫

Mantineでのレスポンシブ

2022/04/18に公開

mantineでレスポンシブ対応するときに[`@media (max-width: ${theme.breakpoints.xl}px)`]といちいち書くのはめんどくさい🙃
せっかくthemeで設定しているのに使えないわけはないのでは?🤔となり調べた


該当ページと該当コード

https://mantine.dev/theming/responsive/#media-queries-in-createstyles

import { createStyles } from '@mantine/core';

const useStyles = createStyles((theme) => ({
  container: {
    height: 100,
    backgroundColor: theme.colors.blue[6],

    // Media query with value from theme
    [`@media (max-width: ${theme.breakpoints.xl}px)`]: {
      backgroundColor: theme.colors.pink[6],
    },

    // Static media query
    '@media (max-width: 800px)': {
      backgroundColor: theme.colors.orange[6],
    },
  },
}));

function Demo() {
  const { classes } = useStyles();
  return <div className={classes.container} />;
}

結論 theme functionを使えばいける😎

https://mantine.dev/theming/functions/#smallerthan-and-largerthan
Responsive stylesの次のページに書いてあるTheme functionssmallerThanlargerThanを使えばいい

つまり、先程のコードは下記のようにも書ける😎

Media queries in createStyles
import { createStyles } from '@mantine/core';

const useStyles = createStyles((theme) => ({
  container: {
    height: 100,
    backgroundColor: theme.colors.blue[6],

    // Media query with value from theme
-    [`@media (max-width: ${theme.breakpoints.xl}px)`]: {
+    [theme.fn.smallerThan('xl')]: {
      backgroundColor: theme.colors.pink[6],
    },

    // Static media query
-    '@media (max-width: 800px)': {
+    [theme.fn.smallerThan(800)]: {
      backgroundColor: theme.colors.orange[6],
    },
  },
}));

function Demo() {
  const { classes } = useStyles();
  return <div className={classes.container} />;
}

他にも便利な関数があって良き🥰

GitHubで編集を提案

Discussion