LoginSignup
3
3

More than 1 year has passed since last update.

[React]Material UIでレスポンシブ対応

Posted at

本記事の目的

Material UIが@mui/materialからインポートするようになってから、
useStyles,makeStylesの組み合わせの使用が非推奨になりました。
それに伴い、レスポンシブ対応をするには、以前まではtheme.breakpointsを使用するケースが大半だったと思うのですが、それ以外のやり方でレスポンシブ対応させるやり方を調べましたのでまとめます。

やり方は以下の通りです。

①media queryを使用する場合
②useMediaQueryを使用する場合

①media queryを使用する場合

box.tsx

<Box component="div" sx={{
    fontSize: "1rem",
    "@media screen and (min-width:600px)": {
        width: "40%",
    },
}} >
    sample box
</Box>

box.tsx

import { styled } from "@mui/material/styles"
import Box from "@mui/material/Box

const StyledBox = styled(Box)(() => ({
  fontSize: "1rem",
    "@media screen and (min-width:600px)": {
        width: "40%",
    },
}))

sx内に直接書く、ないしはstyledのなかに上記のように書き記すやり方です。

②useMediaQueryを使用する場合

box.tsx

import useMediaQuery from "@mui/material/useMediaQuery"

const SampleBox = () => {
  const matches: boolean = useMediaQuery("(min-width:577px)")
  {matches ? (
     <Box component="div">
            Sample Box
     </Box>
  ) : (
    <Box></Box>
  )}
}

また、Material UIのブレイクポイントを使用しても記載ができます。

const matches: boolean = useMediaQuery(() => theme.breakpoints.up("sm"));

ただ、このやり方だと記述量が非常に多くなってしまうため、おすすめではありません。

参考記事

Material UIでのレスポンシブサイト作成

3
3
1

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
3
3