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

Exploring JqueryUI tab navigation with the help of the <a> tag

I have come across several articles mentioning the possibility of navigating JqueryUI tabs using a button or anchor tag. Here is the method I am currently using: $("#vtabs").tabs(); $("#tabsinner").tabs(); $(".changeTab").click(function() { alert("as ...

Clicking on a button will allow me to select only a portion of text within a specific cell of

Inside a table, there is a paragraph of text enclosed in a <td></td> element. Take for example the following passage. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard ...

Upon updating my application from Angular 14 to 16, I encountered an overwhelming number of errors within the npm packages I had incorporated

After upgrading my angular application from v14 to v16, I encountered numerous peer dependencies issues, which led me to use the --force flag for the upgrade process. However, upon compiling, I am now faced with a multitude of errors as depicted in the scr ...

Setting a CSS style for an ASP.NET button: What you need to know!

I am facing an issue with the styling of my asp:Button. I have applied CSS styles using the cssClass property, but they are not being applied correctly. Surprisingly, when I switch to using asp:LinkButton, the styles work perfectly fine. I prefer not to us ...

Determine the fill color attribute value of a rectangle using Testcafe paired with typescript

Here is a code snippet I need help with: <colored-item label="Label A" symbol-size-left="9.5" symbol-size-right="12" symbol-right="" symbol-left="<svg viewport="0 0 24 24" xmlns="http://www. ...

The menu bar created from getJSON is not displaying the jQuery UI CSS styles as expected

I have been working on creating a jQueryUI menubar using JSON data. The JSON data is successfully being converted into valid HTML, but the menubar does not display with the desired styling. It appears as an unstyled unordered list rather than a styled menu ...

IE6/7 dilemma with CSS floating

Encountering a strange CSS float issue in IE6 and IE7. The HTML code looks like this: <fieldset style="float:left"> <legend>Summary</legend> <div class="display-label">Recruitment type</div> <div class="displa ...

Pricing determined by location on a website created with HTML

We are looking to customize our HTML5/CSS3 website by displaying different pricing tables based on the location of each visitor. Our goal is to have a fixed price for users from Singapore while showing a different price for visitors from other parts of th ...

Tips for ensuring compatibility of CSS in IE7 and IE8

Despite using the following styles to dynamically display alternative colors in my HTML code, I am facing compatibility issues with IE7 and IE8. Surprisingly, everything works perfectly fine on IE9 and above. It seems these styles are not supported by IE7 ...

Tips for attaching a "progress" and refresh event to an ajax call while sending a file

I am currently using the FormData API and AJAX to upload files to a server in PHP-CodeIgniter. The file upload works perfectly when triggered by the file select event. However, I would like to display a progress bar next to each file being uploaded with th ...

Using Vue 3's emit in place of v-model

I am facing a challenge with integrating a custom dropdown select component. The idea is to use v-model to retrieve data from the parent component, but I am unsure how to pass that through an emit. Can anyone clarify this for me? Here is my parent compone ...

Leverage Vue's ability to inject content from one component to another is a

I am currently customizing my admin dashboard (Core-UI) to suit my specific needs. Within this customization, I have an "aside" component where I aim to load MonitorAside.vue whenever the page switches to the Monitor section (done using vue-router). Here ...

Steps for capturing a screenshot of the canvas while utilizing the react-stl-obj-viewer component

I recently started using a component called react-stl-obj-viewer to display a 3D STL image. The rendering of the image itself is working fine. However, I encountered an issue when trying to move the rendered image around and implement a button for capturin ...

Placing an icon and a title on the same baseline

I'm working on a new website design and I really like the layout shown in this image: https://i.stack.imgur.com/QuVRZ.png I've been struggling to align the icon with the title in a responsive manner. Here are some of the approaches I've att ...

What steps can be taken to remove the search parameter responsible for the error?

Imagine having a webpage that displays search results based on the parameters in the URL, like this: https://www.someurl.com/categories/somecategory?brands=brand1,brand2,brand3 This URL will show listings for only brand1, brand2, and brand3. Additionally ...

What are the steps to correct the orientation of Material-UI Select with MenuItem displayed horizontally?

I've been encountering a strange and persistent issue while working with Material-UI in React/Next.js. I am struggling to get the <Select> component to display a regular vertical dropdown menu. How can I ensure that the <MenuItem>s render ...

Node.js - Error: Undefined:0 SyntaxEncountered an unexpected end of input syntax error

Exploring Node.js and Backbone.js for the first time. Using the book "Backbone Blueprints" but encountering issues with the provided code to set up the webserver. Node.js is installed and running fine. Here's the package.json code: { "name": "simp ...

Utilizing Google Language API for bulk translation tasks

My current project involves using Google's AJAX Language API to translate each element in an array. for(var i=0; i < mytext.length; i++) { google.language.translate(mytext[i], originalLanguage, newLanguage, function(result){ if(!result.error){ ...

What is the best way to pass an array through router navigate function?

I've searched for a solution in other questions, but nothing has helped me... My goal is to redirect to a URL like this: this.router.navigateByUrl('/products'); I want to pass an array and retrieve it in the component with the active link ...

Click on the button to automatically scroll to a specific component inside the dialog

In my JSF/Primefaces application, I have a page with a long content that can be scrolled, along with a dialog also containing lengthy content that requires scrolling. The dialog includes a button and I am looking to scroll the dialog content to a specific ...