Home > Enterprise >  How to create clickable progress bar increament and decreament value of progress bar with 20%
How to create clickable progress bar increament and decreament value of progress bar with 20%

Time:10-10

const [complete,setComplete]=useState(0);
handleClick=()=>{
  
 if(complete<100)
{
   setComplete(complete 20);  

}
}
return(

<div className="prentdiv" onClick={handleClick}>
 <div className="childdiv></div>
</div>

)

export default App;

I want to increament value of progressbar by 20% on each click till 100% and again decreament value by 20% till 0 e.g increment 20% 40% 60% 80% 100% decrement again 100% 80% 60% 40% 20%

CodePudding user response:

import { useState } from "react";

function App() {
  const [progress, setProgress] = useState(0);
  const [progressDirection, setProgressDirection] = useState("asc");

  function increment() {
    if (progress === 100) {
      setProgressDirection("desc");
      setProgress(80);
    } else {
      setProgress((currentProgress) => currentProgress   20);
    }
  }
  function decrement() {
    if (progress === 0) {
      setProgressDirection("asc");
      setProgress(20);
    } else {
      setProgress((currentProgress) => currentProgress - 20);
    }
  }
  function handleClick() {
    if (progressDirection === "desc") {
      decrement();
    } else {
      increment();
    }
  }
  return <div className="App">
    <div>{progress}</div>
    <button onClick={handleClick}>Click</button>
  </div>;
}

export default App;

CodePudding user response:

You can do this by manipulating its width as

Live Demo

Codesandbox Demo

App.js

import React, { useState } from 'react';

const App = () => {
    const [isIncrementing, setIsIncrementing] = useState( true );
    const [initialWidth, setInitialWidth] = useState( 20 );

    const changeWidth = () => {
        if ( isIncrementing ) setInitialWidth(oldWidth => oldWidth   20);
        else setInitialWidth(oldWidth => oldWidth - 20);
        if(isIncrementing && initialWidth   20 === 100) setIsIncrementing(false);
        if(!isIncrementing && initialWidth - 20 === 0) setIsIncrementing(true);
    }

    return (
        <div>
            <div className="progress-bar-wrapper" onClick={changeWidth}>
                <div className="progress-bar" style={{ width: `${initialWidth}%` }}></div>
            </div>
        </div>
    );
};

export default App;

CSS

.progress-bar-wrapper{
    width: 300px;
    height: 1rem;
    cursor: pointer;
    border: 1px solid #ccc;
    border-radius: 1rem;
}

.progress-bar{
    background-color: blueviolet;
    border-radius: 1rem;
    height: 100%;
    transition: width ease-out 0.3s;
}
  • Related