The MUI snackbar element lingers in the DOM even after it has been closed

Having created a global modal with the intention of only utilizing it when necessary, I've encountered an issue where the snackbar div persists in the DOM. This persistence is causing certain elements to become blocked as they appear beneath this div. Any insights on what might be causing this problem?

This is my GlobalAlert component:

export function GlobalAlert() {
  const {alertState, handleClose} = useAlertContext();
  const {open, type, message} = alertState;

  function TransitionDown(props: TransitionProps) {
    return <Slide {...props} direction="down" />;
  }

  return (
    <Snackbar
      key={"top" + "center"}
      TransitionComponent={TransitionDown}
      anchorOrigin={{vertical: "top", horizontal: "center"}}
      autoHideDuration={4000}
      disableWindowBlurListener={true}
      open={open}
      onClose={handleClose}
    >
      <Alert severity={type} sx={useStyles.alert} variant="filled" onClose={handleClose}>
        {message}
      </Alert>
    </Snackbar>
  );
}

The context where information is retrieved from:

const AlertContextProvider = (props: any) => {
  const [alertState, setAlertState] = React.useState<AlertState>({
    open: false,
    type: "error",
    message: "",
  });

  const handleClose = React.useCallback((event?: React.SyntheticEvent | Event, reason?: string) => {
    if (reason === "clickaway") {
      return;
    }
    setAlertState({
      open: false,
      type: "error",
      message: "",
    });
  }, []);

  const value = React.useMemo(
    () => ({
      alertState,
      setAlertState,
      handleClose,
    }),
    [alertState, handleClose],
  );

  return <AlertContext.Provider value={value} {...props} />;
};

Reference image for the bug: https://i.stack.imgur.com/5UvCs.png

Answer №1

To address the issue, I included the following line in the Snackbar properties:

ClickAwayListenerProps={{ onClickAway: () => null, }}

I am currently utilizing MUI 5.

For further assistance, you may also want to check out this resource.

Answer №2

Encountered a similar problem with the snackbar functionality. In my case, when the snack bar's autoHideDuration is set, it applies 'visibility: hidden' to an intermediate div block instead of simply hiding it. To work around this issue, I adjusted the style of the snackbar's div block to display 'none' when the snackbar is in a closed state using the sx prop. Here is an example:

<Snackbar
          anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
          open={snackbarOpen}
          autoHideDuration={3000}
          onClose={handleClose}
          message={message}
          TransitionComponent={TransitionLeft}
          //  action={action}
          ContentProps={{
                sx: {background : "green", }
            }}
          sx={{ display : () => snackbarOpen ? 'block' : 'none'} } 
            />
 

View code snippet for setting display to none on close

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting the spacing between characters in SVG text elements

Take a look at this unique SVG: <svg xmlns="http://www.w3.org/2000/svg"> <defs> <style type="text/css"><![CDATA[ .code { font-family: monospace; white-space: pre; tab-size: 4; } ]]></style> </defs> <text class="cod ...

Enhance your web forms with jQuery Chosen's automatic formatting feature

Having trouble adding a feature to my multi-select input box using jQuery Chosen. The current functionality allows users to enter custom values not in the list. The new feature should automatically format numbers entered by users, for example: User input ...

Styling Collapse Text in Bootstrap Framework

I have a question about the "Accordion example" in the Bootstrap Collapse Component. My query is regarding removing the underline from the text "Collapsible Group Item" 1-3 when they are activated. Normally, this text is not underlined, but upon hovering, ...

I am experiencing issues with my JavaScript not functioning properly in conjunction with my HTML and CSS. I am uncertain about the root cause of the problem (The console is displaying an error message:

I am facing challenges in creating a content slider and encountering issues with its functionality. Specifically, when testing locally, I noticed that the current-slide fades out and back in upon clicking the arrows left or right, but the slide content is ...

Unable to modify array state with data from another state

Two state objects are at play here. The first is personnel, which consists of an array of 1-object arrays structured like this: [[{}],[{}],[{}],[{}],...]. The second state object is rowItems, where the goal is to extract all objects from the inner arrays o ...

The Meteor API call occurs after rendering but before componentwillmount

I am currently facing an issue with async. It appears that the render function is being called before the api call completes in the componentwillmount // Framework import React, { PureComponent } from "react"; // Components import Page from "../component ...

The Bootstrap 3 Navbar displays a #EEEEEE color when a link is hovered over

I have not specified a hover color in the stylesheet for links to be #EEEEEE. I want the navbar hover effect to blend in with the navbar background, creating a seamless transition when hovered over. For reference, here is my current stylesheet code: Paste ...

Code is not running in ReactJS

My challenge is to use canvas and script to draw a rectangle with one diagonal line. However, when I try to do so, only the rectangle appears on my browser. It seems like the script is not being executed. Here's the code: import React, { Component } ...

Unable to delete React element by ID as it is undefined

Having some trouble deleting an item by ID with React. Despite the backend routes functioning properly (node and postgresql), every attempt to delete an item results in it reappearing upon page refresh. The command line indicates that the item being delete ...

Updating the layout when transitioning between routes in Next.js 14 using the AppRouter design concept

I am a beginner in next.js and I want to create a navigation bar that can be shared between components using the approuter concept. I am currently working with next.js version "14.0.2". The folder structure mentioned below in the image https://i.stack.im ...

What is the proper way to apply a custom format to a NumberFormat within a Material-UI TextField?

I'm currently working with a Mui Textfield and I want to be able to use custom formats that can be passed as a prop. My challenge is figuring out how to pass these custom formats effectively. I came across an online sandbox that showcases the usage of ...

Personalized Bootstrap 4.1 Toggle Animation

I have been attempting to implement a customized menu toggle on Bootstrap 4.0's Navbar menu, using the code provided by Codeply HERE. My goal is to apply the X toggle style to my website's bootstrap navbar. Below is the current setup I have imple ...

How to Customize the Drawer Color in Material-UI v5

I'm currently using MUI v5 in my project and I am encountering some challenges while attempting to style a Drawer component with a black background color. As this update is relatively new, I have not been able to find much information on customizing t ...

What could be causing a compile error in my React and TypeScript application?

I recently downloaded an app (which works in the sandbox) from this link: https://codesandbox.io/s/wbkd-react-flow-forked-78hxw4 However, when I try to run it locally using: npm install followed by: npm start I encounter the following error message: T ...

Using jQuery to modify a CSS property when a specific option is chosen

I'm currently working on creating an option dropdown menu and I've hit a roadblock trying to display a textbox only when the 'other' option is selected. Here's what I have so far: <span id="con-country"><label for="count ...

Discover the hexadecimal color code generated from an rgba color

Do you know of a service that can determine the final hexadecimal value of an rgba color? For instance, if my body background-color is set to #FF0000 and my header is positioned over it with a background-color of rgba(0,0,0,.7), how can I find out what the ...

Using Next.js to Retrieve JSON Data and Render it in Components

I want to refactor the MainMenu function and getStaticProps from index.js into separate components. Here is my current index.js page that is functioning correctly. #index.js import Link from 'next/link'; function MainMenu({ menuLists }) { re ...

Guide to deploying a React Application to Netlify while organizing the client and server directories

I'm facing some confusion while attempting to deploy an application to Netlify that consists of both client and server folders. I initially tried running npm build on the main directory which contains both folders, but it did not yield the desired res ...

I'm attempting to create a dropdown menu, but I'm struggling to keep it open when I hover over an option

Seeking assistance as a beginner in coding. I am struggling with creating a dropdown menu option on my website. The issue is that the menu closes whenever I attempt to move my mouse to select other options. It seems to work fine when using the run option h ...

Displaying the age figure in JSX code with a red and bold formatting

I have a webpage with a button labeled "Increase Age". Every time this button is clicked, the person's age increases. How can I ensure that once the age surpasses 10, it is displayed in bold text on a red background? This should be implemented below t ...