myTest532 myTest532
myTest532 myTest532

Reputation: 2381

Create simple custom progression bar in React

I'm trying to create my simple progression bar in React using CSS and setInterval. It's not working properly after 10%. Does anyone know why it is happening? Thanks

import React, {useState, useEffect} from 'react';

const Loading = () => {

    const [percentage, setPercentage] = useState(0);

    const containerStyles = {
        height: 20,
        width: '100%',
        backgroundColor: "#e0e0de",
        borderRadius: 50,
        margin: 50
    }

    const fillerStyles = {
        height: '100%',
        width: `${percentage.toString()}%`,
        backgroundColor: 'red',
        borderRadius: 'inherit',
        textAlign: 'right'
    }

    const labelStyles = {
        padding: 5,
        color: 'white',
        fontWeight: 'bold'
    }

    useEffect(() => {
        const newPercentage = parseInt(percentage) + 1;
        setInterval(() => setPercentage(newPercentage), 1000);
    }, [percentage])

    return (
        <div style={containerStyles}>
            <div style={fillerStyles}>
                <span style={labelStyles}>{percentage}%</span>
            </div>
        </div>
    )
}

export default Loading;

Upvotes: 0

Views: 167

Answers (1)

Nitsan Cohen
Nitsan Cohen

Reputation: 697

You should store your interval in a constant and use the cleanup function to clear the last interval each time.

I'd also change how you handle setPercentage and use timeout instead of interval

Something like this:



useEffect(() => {
     const timeoutID = setTimeout(() => 
        setPercentage(prevPercentage => prevPercentage + 1)
      , 1000);
   
      return () => clearTimeout(timeoutID);
  }, [setPercentage]);

Upvotes: 1

Related Questions