Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React MUI – make a dialog appear on small screens – invalid hook call

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
  );
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading