Kuan
Kuan

Reputation: 11389

Css transition does not work for the first run in React

I made a progress bar component:

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

var ProgressBar = ({percentage, duration}) => {
    
let [style, setStyle] = useState({
    "position":"relative"
})
useEffect(()=>{
        setStyle({
            "top":"0px",
            "position":"relative",
            "height":"100%",
            "backgroundColor": "lightblue",
            "color": "lightgrey",
            "left": "0px",
            "transition": `width ${duration}s`,
            "width": percentage+"%"
        });
}, [])
var cntStyle = {
    "display": "block",
    "width": "150px",
    "left":"0px",
    "backgroundColor":"grey",
    "height":"15px",
    "position": "relative"
}

    return (
        <div className="progressbar-container" 
        style={cntStyle}>
            <div className="progress" style={style}></div>
        </div>
    );
}

export default ProgressBar;

And use it like

<ProgressBar 
    percentage="80" 
    duration="5"  />

I wonder why the transition does not work. It directly show 80% progress bar.

Upvotes: 1

Views: 285

Answers (1)

Tasos
Tasos

Reputation: 2036

This doesn't work because there is no initial value of the width to transition from.

"CSS transitions allows you to change property values smoothly, over a given duration." read more here

This transition should work if you change the percentage from one value(0) to another(80).

A workaround for this would be to update the component prop with an interval or initialize the component style with the value 0 for the progress bar width

Upvotes: 1

Related Questions