What potential factors could lead to an MUI Snackbar failing to produce the accurate class names?

I am facing an issue with displaying notifications on my Gatsby blog whenever the service worker updates. I am using a MUI Snackbar toast for this purpose. However, sometimes the styling of the toast is not applied correctly and it ends up looking like this:

https://i.stack.imgur.com/Cvw4X.png

It should actually look like this:

https://i.stack.imgur.com/RsTwl.png

After examining the code, I noticed that the <Snackbar> and MUIAlert components are not outputting the correct classes on their respective div elements.

The relevant code snippet is as follows:

export default function Layout({ children }: { children: ReactNode }): ReactElement {
  const [toastOpenState, setToastOpenState] = React.useState(isBrowser() && Boolean(localStorage.getItem('serviceWorkerUpdated')));

  function handleToastClose(): void {
    setToastOpenState(false);
  }

  return (
    <>
      <TopNav/>

      <Snackbar className="toast"
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
        open={toastOpenState}
        onClose={handleToastClose}
        TransitionComponent={Transition}
      >
        <MuiAlert severity="success" variant="filled" elevation={6} onClose={handleToastClose}>
          A new version is available.
          <Button onClick={() => {
            localStorage.removeItem('serviceWorkerUpdated');
            window.location.reload();
          }}>Reload</Button>
        </MuiAlert>
      </Snackbar>

      <div style={{ flex: 1, margin: '0 1em' }}>
        {children}
      </div>
      <Footer />
    </>
  );
}

Answer №1

The fix involved relocating the code that changes the open status of the toast to true from an onEffect hook:

  const [toastOpenState, setToastOpenState] = React.useState(false);
  useEffect(() => {
    if (localStorage.getItem('serviceWorkerUpdated'))
      setToastOpenState(true);
  }, []);

  // Function called when the close button is clicked
  function handleToastClose(): void {
    setToastOpenState(false);
  }

  return (
    <>
      ... same content
    </>
  );
}

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

jQuery "slide" animation without using <br>

I've been working on a website that incorporates the jQuery "Slide" effect. I have implemented this effect multiple times, using it on 3 different div tags. Each line consists of one "Dynamic" div tag (the moving one) and one "Static" div tag (the tri ...

Where the package.json file resides

Is there a designated location for the package.json file in a project, like within the project directory? Where should the package.json file be located in a multi-component project? What is the significance of having version 0.0.0 in th ...

My React setup is causing some problems that I need to address

React is not my strong suit, but I need to test a React application. The issue arises when attempting to run the server using gulp nodemon, resulting in numerous errors. It seems that the application is built on an outdated version of React and some libra ...

Automatically fill in the Modal popup

Today, I encountered a challenge while trying to keep the current page in a jQuery data table. Clicking on the "Edit" link in a row would open a modal pop-up and fill in the controls. However, this action resulted in a postback that set the page back to pa ...

What is the best way to receive a single response for various API endpoints?

I need to retrieve a single response from an API that has multiple page URLs. How can I accomplish this with just one API call? Here is my code: async function fetchArray () { // Fetch `urlArray` from object parameter let urlArray = []; ...

TinyMCE - Optimal Approach for Saving Changes: keyup vs onChange vs blur

In the context of my Filemaker file, I am utilizing the TinyMCE editor. My goal is to automatically save any changes made by the user, whether it's typing, applying formatting, inserting an image, or making any other modifications. I have a function ...

Troubleshooting the failure of implementing react hooks useState within a material-ui Tab container

Recently, I have been experimenting with implementing react-hooks useState in material-ui/tabs component. While I have been successful in using the handleChange function, I am eager to explore and master the use of hooks in this scenario. Interestingly, my ...

Ways to create a smooth transition in element height without a known fixed target height

Is it possible to create a smooth height transition for an element when the target height is unknown? Replacing height: unset with height: 100px allows the animation to work, but this presents a problem as the height needs to be based on content and may v ...

Encountering an error while trying to run a Next.js application on Linux Mint

View the error screenshot After creating a new Next.js app with npx create-next-app, I ran npm run dev and encountered the following error message ...

Select elements from a PHP loop

As part of my school project, I am developing a basic webshop. Currently, I am using a while loop to display featured products on the homepage. However, I now need to implement a shopping cart functionality. After a user clicks the "add to cart" button, th ...

Steps to create a continuous blinking/flickering effect on a highchart pathfill

I am currently utilizing highcharts within one of my applications. I want to emphasize a particular stroke based on the content, and while I have achieved this already, I now need it to blink or flicker as if indicating an issue at that specific point. C ...

Implementing the useState hooks in an asynchronous callback

I'm currently running an asynchronous operation with a callback function (using IPFS in this scenario, though the specific tool isn't crucial), and am attempting to update state using hooks within that callback. However, for some reason the code ...

I am searching for a straightforward Rails sample that incorporates Ajax

Currently, I am on a quest to find a solid demonstration of how AJAX and JSON interact with Rails. I have a Rails application that relies on standard forms and I am looking to enhance it with some ajax functionality. Unfortunately, I haven't come acro ...

Creating a Dynamic Slideshow on Autopilot

My JavaScript skills are not perfect and I'm feeling a bit lost. I have this code for a slideshow, but I want to make it automatic while also allowing users to navigate between images freely. I'm struggling to figure out how to implement this fun ...

The total size of the React JS bundle is 1.9 megabytes

Looking for ways to decrease the size of my bundle.js file, which is currently 1.9mb. Any suggestions on how I can further reduce it? I have already implemented lazy loading and managed to lower it from 2.3mb to 1.9mb. ...

Prevent users from adding or removing any letters

Exploring the ACE Editor integration with AngularJS (utilizing UI-Ace). I have a question. Is it possible to limit the user's actions to: Only allow entering a predefined character (for example, ;) Prevent deletion of any characters except for the p ...

Connecting JSON objects based on unique GUID values generated

I am in search of a method to automate the laborious task of linking multiple JSON objects with random GUIDs. The JSON files are all interconnected: { "name": "some.interesting.name", "description": "helpful desc ...

Learn the process of incorporating a new object property into the state update in React

I am attempting to add a new property called "id" to the state object named formData. However, my current approach is not yielding the desired results. The current structure of the formData object is as follows: { Fname : Tony Lname : Stark } My goal is ...

React Native: Triggering a Parent Component Rerender from a Child Component Event

There are two components in my setup. Main Component : App.js Sub-component : Logitem.js The Main Component displays a list of Sub-components. Each Sub-component contains a text element that, when clicked, triggers a modal display. The modal comprises ...

Converting a PHP timestamp to a jQuery-compatible format

Can someone help me find the equivalent function in jQuery that will give me a time format similar to this: date( 'Y-m-d\TH:i:sP'); //the output is like this. 2013-10-30T18:10:28+01:00 I am looking for this specific format in jQuery to use ...