Home > Net >  Material UI Typography & Media Queries in
Material UI Typography & Media Queries in

Time:03-08

below in the typography component, i wanted to make the variant prop dynamic in accordance to the different screen widths , how it can be done?? appreciate your feedback

import { useTheme, useMediaQuery } from "@material-ui/core";

const Home = () => {
  const classes = useStyles();
  const theme = useTheme();
  const MQlg = useMediaQuery(theme.breakpoints.down("lg"));
  const MQmd = useMediaQuery(theme.breakpoints.down("md"));
  const MQsm = useMediaQuery(theme.breakpoints.down("sm"));

<Typography
          variant={`${MQsm && "h4"}   ${MQmd && "h3"}  $ {MQlg && "h2"} `}
          className={classes.text}
          gutterBottom
        >
          pioneering
</Typography>

CodePudding user response:

Following the example on this MUI page for useMediaQuery, please see what I have created to assist you:

import * as React from "react";
import { createTheme, ThemeProvider, useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
import { Typography } from "@material-ui/core";
function MyComponent() {
  const theme = useTheme();
  const large = useMediaQuery(theme.breakpoints.up("lg"));
  const medium = useMediaQuery(theme.breakpoints.up("md"));
  const small = useMediaQuery(theme.breakpoints.up("sm"));

  return (
    <>
      <div>{`large: ${large}`}</div>
      <div>{`medium: ${medium}`}</div>
      <div>{`small: ${small}`}</div>
      <Typography
        variant={large ? "h1" : medium ? "h2" : small ? "h3" : "body1"}
      >
        Font Size Change
      </Typography>
    </>
  );
}

const theme = createTheme();

export default function ThemeHelper() {
  return (
    <ThemeProvider theme={theme}>
      <MyComponent />
    </ThemeProvider>
  );
}

Inspect the page, and change the sizes for the screen. Some will appear true, whilst other's false.

  • Related