Material UI: use media query outside component

Viewed 711

I am working on React app with Material-UI.

Is there any way to use media query or determine viewport width in React/Material-UI way outside a component body?

I need to set default props for a component based on viewport size.

For now, I am handling it with windows.innerWidth as below.

const defaultProps = {
  textVariant: window.innerWidth < 600 ? 'body1' : 'h4',
}

const Text = (props)  => {
    ...
}

Text.defaultProps = defaultProps;

Is there any Material-UI utility that can be used in setting default props based on viewport size?

1 Answers

No. window width can be changed when you resize the browser window, putting the code outside like that will compute the textVariant value at compile time. while using useMediaQuery or useWindowSize will listen to the resize event and give you the correct width value at runtime.

What you can do instead is to store the default value as a state and update that value when the window size changes. Below is the minimal example:

function useVariant(variant?: Variant) {
  const [defaultVariant, setDefaultVariant] = useState<Variant>("h6");
  const largeScreen = useMediaQuery("(min-width:600px)");

  useEffect(() => {
    if (largeScreen) {
      setDefaultVariant("h5");
    } else {
      setDefaultVariant("h6");
    }
  }, [largeScreen]);

  return variant || defaultVariant;
}

export default function Types(props) {
  const variant = useVariant(props.variant);

  return (
    <Typography variant={variant}>
      Resize window to see text size changed
    </Typography>
  );
}

Live Demo

Edit Material demo (forked)

Related