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

Unable to attach an onClick event handler to <TableRowColumn> element using Material-UI in React

In the past, I had a feature that allowed me to change the color of the text from red to green by clicking on a table cell. After introducing Material-UI in my React app and replacing the <td> tags with <TableRowColumn> tags, I noticed that th ...

Enhancing transparency with a touch of background color

After successfully exporting my chart created in canvas as an image file, I noticed that the image turned out to be transparent without any background. Is there a way through code to add a background color to this existing image obtained from canvas? For ...

The property this.props.Values is not defined

I'm facing an issue with a page. Specifically, I am working with the value: this.props.CategoriesList. This value represents a list of categories. The problem is that when I click on a button to navigate to the page where this value is used, it shows ...

ReactJS Application: Issue with Selective Mobile Scrolling

I've been working on a ReactJS web app where we mainly use styled-components for styling, but also sometimes utilize index.css for global styles (such as body and html). The application consists of an app header, a page header, and a container with a ...

Unable to show information post retrieval

My current challenge involves fetching data from a REST endpoint using axios, rendering it in my app.js component, and then sharing it with the entire app through the context API: axios.js import axios from 'axios'; const instance = axios.crea ...

Experience seamless page transitions with React Router v4's sleek animation that smoothly guides you

I implemented a fade-in fade-out transition for routed components using RR4 and ReactCSSTransitionGroup, based on the example provided in https://reacttraining.com/react-router/web/example/animated-transitions While the animations are working, I am facing ...

Every time I submit a stateful form in React with Netlify integration, I always seem to

I've created a form using React and Bulma. Now I wanted to incorporate Netlify and just use their form handling. I've included 'data-netlify'='true' and 'data-netlify-honeypot'='bot-field' and used their su ...

Implement Material UI Textfield with 'error' and 'helper text' for items within a repeated loop

I am currently working on developing an application that involves dynamic text field input using MUI textfield. This application consists of two fields - From and To. The functionality includes generating two new fields when the user clicks on the "Add New ...

Adjusting Dropdown Direction Based on Section Location – A Step-by-Step Guide

Question: Is there a way to adjust the bootstrap dropdown so that it can appear either above or below depending on where the section is positioned? Check out my code here Here is the CSS I am using: #cover-inspiration{ width: 100%; height: 100vh ...

While continuing to input text, make sure to highlight a specific element from the search results list

Currently, I am using a customized search feature in my React.js application. I am looking for a way to focus on an element within the search results so that I can navigate using arrow keys. At the same time, I need to keep the input field focused to conti ...

Is it possible to incorporate custom icons with Blueprintjs components?

Exploring the idea of incorporating Blueprintjs into an upcoming project. Wondering if it's feasible to integrate custom SVG icons in the button, menu and navbar components? Existing examples seem to be focused on using the default icon set. The app ...

Is there a way to display icons alongside each option in the dropdown menu?

I have a dropdown icon (pumpkin 1) div that is causing spacing issues with the other icons on the page. The problem is that it has a dropdown functionality which needs to overlay the text at the bottom. I want to display all icons next to each other (1,2, ...

The issue with Icons not displaying in MaterialTable when using the Fuse template

I'm currently working on a project that utilizes MaterialTable from material-ui, but I'm facing an issue where the icons are not being displayed. Within my page, I have imported the following: import MaterialTable, { Column } from 'material ...

Using react-select to display "N items selected" instead of listing out all the selected items

Exploring the potential of react-select as a city-picker selector for users to choose one or multiple cities to filter data. Take a look at how it appears on my page: The list of cities may be extensive, and I am concerned about the selector expanding bey ...

Unable to submit form data in AWS Amplify & React: The message "Not Authorized to access createRecipe on type Mutation" is displaying

I've recently set up a project using React and AWS Amplify. I've successfully added some data to DynamoDB in AWS, but when I try to submit form data from my React App, I encounter an error from the API. I'm a bit stuck on what to do next. I ...

Unable to update state in my React app when clicking on a button

There is a requirement for a button click to filter the job-card array by one specific category. For example, clicking on the button "Marketing" should only show jobs from the array that have the property "jobstags: Marketing". I followed a similar procedu ...

Is the child constantly updating due to a function call?

Having difficulty navigating the intricacies where a child keeps re-rendering due to passing a function from the parent, which in turn references an editor's value in draftjs. function Parent() { const [doSomethingValue, setDoSomethingValue] = Re ...

Exploring the contrast between router.pathname and router.route within Next.js

Essentially, my goal is to utilize the NextJS router to access the page url by doing the following: import { useRouter } from "next/router"; const SomeComp = props => { const router = useRouter(); } Yet, when I console.log() the propertie ...

Utilize Vue.js to sort by price bracket and category

Hello, I am currently new to working with Vue.js and I am attempting to create two filters - one for price range and the other for genre. Any guidance or assistance would be greatly appreciated. Below is a snippet of my code: ul class="filter-wrapper"&g ...

Right and left floating elements align side by side

The alignment of the images and file labels needs adjustment to ensure they all appear on the same line. Below is the code snippet that I have tried: HTML: <div> <img src="{{asset('bundles/cramifaccueil/images/pdfdocument.png')} ...