Is there a way to synchronize the autohide duration for both the LinearProgress MUI and SnackBar components?

Can someone help me align my SnackBar with the LinearProgress so that they both have an auto-hide duration of 4 seconds? I've been struggling to figure it out for hours and haven't found a solution yet. Could the issue be in the useEffect part of my code where I set up the progress interval? Any suggestions would be greatly appreciated since I'm new to this. Thank you!

This is the code I'm currently using:

interface SuccessMessageProps {
    open: boolean;
    onClose: () => void;
    title?: string; 
    message?: string; 
  }
  
  const SlideTransition = (props: SlideProps) => <Slide {...props} direction="left" />;
  
  export const SuccessMessage = ({
    open,
    onClose,
    title = 'Title', 
    message = 'Insert message here' } : SuccessMessageProps ) => {
  
    const { palette } = useTheme();
  
    const [progress, setProgress] = useState(0);
    const [showLinearProgress, setShowLinearProgress] = useState(false);
  
    const handleClose = (): void => {
      onClose(); 
    };
  
    useEffect(() => {
      const timer = setInterval(() => {
        setProgress((oldProgress) => {
          if (oldProgress === 100) {
            return 0;
          }
          const diff = Math.random() * 15;
          return Math.min(oldProgress + diff, 100);
        });
      }, 400);
      return () => {
        clearInterval(timer);
      };
    }, []);
  
    return (
      <Snackbar
        open={open}
        autoHideDuration={4000}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
        TransitionComponent={SlideTransition}
        onClose={handleClose}
      >
        <div>
          <Alert
            sx={{
                  width: '487px',
                  height: '104px',
                  paddingTop: '20px',
                  paddingLeft: '20px',
                  backgroundColor: '#FDFDFD',
            }}
            icon={(
              <Stack
                justifyContent="center"
                alignItems="center"
                style={{
              borderRadius: '100%',
              backgroundColor: alpha(palette.success.main, 0.10),
              width: '48px',
              height: '48px',
                }}
              >
                <CheckIcon
                  size={24}
                  color={palette.success.main}
                />
              </Stack>
            )}
            onClose={handleClose}
          >
            <AlertTitle sx={{ paddingRight:'80px' }}>
              <Typography variant='headings.h4'>{title}</Typography>
            </AlertTitle>
            <Typography variant='captions.default'>{message}</Typography>
          </Alert>
          {!showLinearProgress && <LinearProgress variant="determinate" sx={{ color:'#222221' }} value={progress} />}
        </div>
      </Snackbar>
      );
    };
  

Answer №1

To begin, we must determine:

  • The percentage represented by each step on the progress bar, as the value passed to the prop corresponds to 0 - 100%
  • Subsequently, we increment this step until reaching 100% on the bar or until the 4-second time limit is reached
  • At the start of the interval, we display the snack bar state as visible and at the end, we revert it to hidden, resetting the progress bar value back to 0

Note: There's a useful react library that could assist with similar issues in the future

Here's the implementation I managed to create:

const [snackbarVisibility, setSnackbarVisibility] = useState(false);
const [progress, setProgress] = useState(0);

const handleAction = () => {
  setSnackbarVisibility(true);

  // Calculating 10ms as 0.25% of 4000ms
  const interval = setInterval(() => {
    setProgress((prevProgress) => prevProgress + 0.25);
  }, 10);
  
  setTimeout(() => {
    clearInterval(interval);
    setSnackbarVisibility(false);
    setProgress(0);
  }, 4000);

  return () => {
    clearTimeout(duration);
  };
};

return (
  <>
    <Snackbar open={snackbarVisibility} />
    <LinearProgress
      value={progress}
      valueBuffer={progress}
      variant="determinate"
    />
    <Button onClick={handleAction}>Start</Button>
  </>
);

Further optimization is definitely possible.
MUI Snackbar API
MUI LinearProgress API

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

Using finally() to correctly construct a Javascript promise

Currently, I am working on an Express API that utilizes the mssql package. If I neglect to execute sql.close(), an error is triggered displaying: Error: Global connection already exists. Call sql.close() first. I aim to keep the endpoints simple and e ...

dojo.xhrGet evaluating script tags

I have a piece of code that is similar to the following: var targetElem = dojo.byId('xyz'); var xhrArgs = { url: 'Welcome.do?call=JS', preventCache: true, load: function(data){ targetElem.innerHTML = data; dojo.parser.par ...

Tips for including numerous hyperlinks in a single row for a website's navigation menu

I need assistance in creating a navigation bar for my website that includes multiple headers with links. I am not sure if the issue lies within my CSS, HTML, or both. Can someone please help me troubleshoot? index.html <!DOCTYPE html> <html> ...

Display information using an ASP.Net barcode scanner

Currently, I am developing a WCF service application that involves receiving characters from a barcode reader and displaying the data on the UI for the user. My issue arises when inputting data using the keyboard into a textbox; everything functions corr ...

Writing a function to determine if an HTML element is present

Is there a way to create a function that checks for the existence of an element with a specific id? I have a list of IDs stored in an array: let CartArray = ["cart-0", "cart-1", "cart-2", "cart-3"]; This is the Java ...

Allow users to interact with table rows by making them clickable and sending a post parameter to a jQuery

After creating a table and populating it with elements using JSTL tags and EL expressions, the next step is to make each row clickable. This can be achieved by implementing the following function: $("tr").click(function() { window.location.href = $(th ...

Struggling to access specific data within a JSON object? Wondering how to extract and display data from a JSON object in VUE?

Despite my extensive searching on Stack and the internet, I have not been able to find a solution to my problem. Currently, I am attempting to retrieve data from a JSON file located in the Vue src folder. The file contains three arrays with names that inc ...

The HTML iframe is displaying blank content

I'm trying to embed a webpage within another webpage using an iframe. I attempted to do so with this simple code: <iframe src="http://edition.cnn.com/" id="i_frame"></iframe> JSFIDDLE However, nothing is displaying. Any thoughts on why ...

The issue persists with Angular's overflow hidden not functioning properly, and similarly, the show password button is

I created a login page using Angular Material, but I'm facing some issues. The problem is that when I set the style overflow: hidden, the show password button stops working. Additionally, if I click the button twice, the webpage refreshes, which shoul ...

Developing a feature that allows users to switch between different sets of information

I'm currently exploring a new project and attempting to design a toggle that switches between monthly and annual payments based on the user's selection, much like the functionality found here: . At present, I have implemented two sets of price c ...

What steps should I follow to make a sticker adhere to a div?

I'm currently in the process of designing a sticker that attaches to the top of a div, much like this: <div className="upgrade-premium"> <div className="upgrade-team"> <h1>Premium</h1> <p>100 ...

Step by step guide on inserting a message (memo/sticky note) onto an HTML page

Wondering how to accomplish this: I've designed an HTML5 homepage and I'm looking to display a message to visitors, such as "Dear visitor, I am currently on vacation from....", in the form of a memo or sticky note positioned in the top right cor ...

Exploring Node.js and JSON: Retrieving specific object attributes

Utilizing ExpressJS, NodeJS, and Bookshelf.js In an attempt to display a user's list of friends, encountering the error "Unhandled rejection TypeError: Cannot read property 'friends' of undefined" when trying to access a property of the obj ...

Running a JavaScript file from Docker to fill a MongoDB database is not working when using the WSL shell on Windows 10

I'm facing some issues while trying to populate my MongoDB using a script. Every time I run the script, I encounter errors even though the Docker container is up and running. For reference, I'm on Windows 10 using WSL shell. https://i.stack.img ...

Change the value of the checked property to modify the checked status

This is a miniCalculator project. In this mini calculator, I am trying to calculate the operation when the "calculate" button is pressed. However, in order for the calculations to run correctly in the operations.component.ts file, I need to toggle the val ...

Placing the navigation bar on the right side of the section

.middle-site-content-container { width: auto; height: auto; border: 2px red solid; display: flex; /*Le pot pozitiona in line*/ flex-wrap: wrap; justify-content: center; flex-direction: row; margin: auto; } .middle-site-content-1, .middle ...

Introducing a Node JS web application unaccompanied by hosting services

As I prepare for a coding competition and want to display my computer's IP address, I am wondering if it is safe to type in my home computer's IP once I start serving the webapp before leaving my house. Apologies if this question seems silly. ...

What is the correct way to run npm and node on Windows 11? I keep encountering an error when attempting to execute npm install on my Windows system

I am encountering an error message when attempting to execute npm install or npm install nodejs-java on my Windows 11 system. Here are the versions: npm version - 9.6.1 node version - v18.15.0 Visual studio - 2017 Despite multiple attempts, I have been u ...

Ways to extract the ASP.net variable value and place it inside a JavaScript textbox

Currently, I'm in the process of developing Javascript code for an ASP.net page. Within my coding framework, the string "foo" is linked to a string variable called myString. In order to transfer the value of myString to a JavaScript variable, I incl ...

The React loader fails to function properly when used with nested routes

I'm currently working on my App.js file where I have defined all the routes for my application. I wanted to implement React-Router data loader functionality. import React from 'react' import { Routes, Route, Navigate, RouterProvider, createB ...