0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[React] MUI - ボタン押下後にMenuコンポーネントでメニューを開いた後、メニュー枠外をクリックしても閉じない現象を解消する方法

Posted at

はじめに

今回、MUIの勉強中にタイトルのような現象が起きて結構詰まってしまい、先日対処法を見つけたので備忘録として残しておきます。

結論

MenuコンポーネントのPropsのonCloseを指定する

import { IconButton, Box, Menu, MenuItem } from "@mui/material";

import IcFlagEnSVG from "@/assets/icons/ic_flag_en.svg";

import React, { useState } from "react";

export const LanguageSelector = () => {
    const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
    const open = Boolean(anchorEl);

    const handleOpen = (e: React.MouseEvent<HTMLElement>) => {
        setAnchorEl(e.currentTarget);
    };

    const handleClose = () => {
        setAnchorEl(null);
    };

    return (
        <>
            <IconButton sx={{ width: 40, height: 40 }} onClick={handleOpen}>
                <Box component="img" src={IcFlagEnSVG} alt="country flag" sx={{ width: "24px" }} />
            </IconButton>
            // ↓onCloseを追記!
            <Menu open={open} anchorEl={anchorEl} variant="selectedMenu" onClose={handleClose}>
                <MenuItem onClick={handleClose} selected>
                    English
                </MenuItem>
                <MenuItem onClick={handleClose}>German</MenuItem>
                <MenuItem onClick={handleClose}>French</MenuItem>
            </Menu>
        </>
    );
};

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?