danH
danH

Reputation: 105

Progress bar in React js

Losing my brain here probably too much for the day but hope you can help with this, I want this progress bar to inherit data from a .json file that has a list of different percentages for the progress bar, eg:

[
  {
    "id": "1",
    "newpercent": "89"
  }
]

How can I add it to my component and use data from .json? I have an empty variable declared as a percentage in the class newPercentage that I want it to be equal to a value from .json.

import React, { Component } from 'react';
import { Line } from 'rc-progress';



class BannerMidProgress extends Component {
  constructor() {
    super();
    this.state = {
      percent: 0,
    };
    this.increase = this.increase.bind(this);
  }
  componentDidMount() {
    this.increase();
  }
  

  increase() {
    
    let newPercent;
    if (newPercent >= 100) {
      clearTimeout(this.tm);
      return;
    }
    this.setState({ percent: newPercent });
    this.tm = setTimeout(this.increase, 10);
  }


  render() {
    const { percent } = this.state;
    return (
      <div style={{ margin: 10, width: 450 }}>
        <Line strokeWidth="1" percent={percent} />
      </div>
    );
  }
}


export  BannerMidProgress
<div className="progressBars">
    <BannerMidProgress />
</div>

Upvotes: 0

Views: 962

Answers (1)

J. K. Kim
J. K. Kim

Reputation: 21

You can import json files like:

import data from "./data.json"

and use it like:

this.state = { percent: data.percent }

But regarding your code, if your intention was to have the progress bar increase until the percent is 100, then there are some issues at the moment. The current code is not incrementing newPercent at all. Hence it will continuously call increase() with newPercent equal to whatever it was set to initially thus never hitting the newPercent >= 100 condition. So the fix for that is the following:

increase() {
  if (this.state.percent >= 100) {
    clearTimeout(this.tm);
    return;
  }
  this.setState({ percent: this.state.percent + 1 });
  this.tm = setTimeout(this.increase, 100);
}

Upvotes: 2

Related Questions