I need to show a dialog only on small screens. After researching I found out that there is a hook called useMediaQuery() which returns a boolean if the browser meets a specific resolution.
I’m using "@mui/material": "^5.1.1"
This is my implementation:
import { useTheme, useMediaQuery, Dialog, DialogTitle } from '@mui/material';
import { useEffect, useState } from 'react';
const MyDialog = () => {
const theme = useTheme();
const [dialogOpen, setDialogOpen] = useState(false);
useEffect(() => {
setDialogOpen(useMediaQuery(theme.breakpoints.down('lg')));
});
return (
<Dialog open={dialogOpen}>
<DialogTitle>This is a test Dialog Title</DialogTitle>
</Dialog>
);
};
However this is giving me the error:
Uncaught Error: Invalid hook call. Hooks can only be called inside of
the body of a function component. This could happen for one of the
following reasons:
It seems it doesn’t allow me to use hooks instide the useEffect hook.
How can I fix it otherwise, in order to achieve the same result, which is to update the useState state true or false according to the resolution of the browser?
>Solution :
You cannot use hooks inside a hook call (useMediaQuery in the callback of useEffect) even though you can use hooks inside another hook definition.
Fix it by moving useMediaQuery to the top level of MyDialog component.
Then use the output value in useEffect.
import { useTheme, useMediaQuery, Dialog, DialogTitle } from "@mui/material";
import { useEffect, useState } from "react";
const MyDialog = () => {
const theme = useTheme();
const [dialogOpen, setDialogOpen] = useState(false);
const matches = useMediaQuery(theme.breakpoints.down("lg"));
useEffect(() => {
setDialogOpen(matches);
});
return (
<Dialog open={dialogOpen}>
<DialogTitle>This is a test Dialog Title</DialogTitle>
</Dialog>
);
};