Reputation: 157
I'm really new with React and having trouble with something. I'm trying to set the a progress bar's progress equal to a variable I have inside of a constructor function in my react component. I'm just using a regular old bootstrap progress bar. The progress bar appears, but no width setting I've tried will actually fill the progress bar. If anyone can help out I'd be grateful. Here's my code:
import React, { Component } from 'react';
import SalesData from '../data/salesData';
class ProgressBar extends Component {
constructor() {
super();
this.ordersInProgress = 0;
this.totalSales = 0;
this.orderGoal = 260;
SalesData.forEach(item => {
this.ordersInProgress += item.orders;
this.totalSales += item.orders * item.price;
});
this.progressBarPercentage = Math.floor((this.ordersInProgress / this.orderGoal) * 100);
this.completedOrders = this.orderGoal - this.ordersInProgress;
}
render() {
return (
<div className="progressBarBlock">
<div className = "progress progressBar">
<div className='progress-bar progressBarColor'
role='progressbar'
aria-valuenow='70'
aria-valuemin='0'
aria-valuemax='100'
styles={{width: this.progressBarPercentage}}>
</div>
</div>
</div>
)
}
}
export default ProgressBar
tldr: I'm trying to set the progress bar progress equal to that progressBarPercentage I've calculated in my constructor function, and it's not filling. Again, thank you in advance for any help you can provide!
Upvotes: 0
Views: 1367
Reputation: 2721
It is not recommemded to you class fields (e.g. this.ordersGoal) to keep data in, especially if your component depends on that data for rendering, as it will not track changes. this.state / this.setState() are designed fro this purpose.
2) It should be style, not styles, as already mentioned above
class ProgressBar extends Component {
constructor() {
super();
let ordersInProgress = 0;
let totalSales = 0;
let orderGoal = 260;
SalesData.forEach(item => {
ordersInProgress += item.orders;
totalSales += item.orders * item.price;
});
const progressBarPercentage = Math.floor((ordersInProgress / orderGoal) * 100);
const completedOrders = orderGoal - ordersInProgress;
this.state = { progressBarPercentage, completedOrders };
}
render() {
return (
<div className="progressBarBlock">
<div className = "progress progressBar">
<div className='progress-bar progressBarColor'
role='progressbar'
aria-valuenow='70'
aria-valuemin='0'
aria-valuemax='100'
style={{width: this.state.progressBarPercentage}}>
</div>
</div>
</div>
)
}
}
export default ProgressBar
3) After a closer study I found numerous problems: 1) data should come as props 2) state is not needed in this case 3) component becomes stateless functional 4) the percentage was always zero due to an error in calculation
This is the sandbox to see it working https://codesandbox.io/s/o51lnz7o99
Upvotes: 0