Search code examples
cssreactjsprogress-barstyling

Inline styling in react (Progressbar progress)


Im trying to style the element with the className "progress", I can't for the life of me figure it out even after trying numerous possibilities.

Any help or hints I can get will be greatly appreciated! Here is the code for component:

  constructor(props) {
    super(props);

    this.state = {
      arrIterator: 0,
      counter: 0,
      sets: props.ids.sets,
      exercises: props.program,
      ids: props.ids
    }

    // Helper variable to decide when a new round starts --> Reset counter
    this.newRoundOn = ((this.state.exercises.length /this.state.sets) -1);

    // Gets percentage for progressbar
    let barPercentage = ((this.state.arrIterator / this.state.exercises.length) * 100) +"%";

    this.style = {
      width: {barPercentage} 
    }
  }

  // Renders Progress Bar
  renderProgressBar() {
    return(
      <div className="card-panel" id="progresjon-panel">
      <div className="row">
          <h5 className="col s8">Progresjon</h5>
          <h5 className="col s4 right-align">{this.state.arrIterator +1} / {this.state.exercises.length}</h5>
      </div>
      <div className="progress" style={style}>
          <div className="determinate"></div>
      </div>
  </div>
    );
  }


Solution

  • You have to modify your state in order to make the progress bar change its value. Check if some property changed using the componentDidUpdate method and then set a new barPercentage value:

    As a small advice, you should avoid passing props to state.

    constructor () {
       this.state = {
         barPercentage: 0
       } 
    }
    
    componentDidUpdate (prevProps) {
      // Helper variable to decide when a new round starts --> Reset counter
      this.newRoundOn = ((this.props.exercises.length /this.props.sets) -1);
    
      // Gets percentage for progressbar
      let barPercentage = (this.props.arrIterator / this.props.exercises.length) * 100;
    
      if (this.props.arrIterator > prevProps.arrIterator) {
        this.setState({ barPercentage })
      }
    }
    
    render () {
      return (
        // [...]
        <div className="progress" style={{ width: `${this.state.barPercentage}%` }}>
          <div className="determinate"></div>
        </div>
        // [...]
      )
    }