spee.ch/react/components/ProgressBar/index.jsx

77 lines
1.9 KiB
React
Raw Normal View History

2018-01-12 02:38:01 +01:00
import React from 'react';
import PropTypes from 'prop-types';
import ActiveStatusBar from 'components/ActiveStatusBar';
import InactiveStatusBar from 'components/InactiveStatusBar';
2018-01-12 02:38:01 +01:00
class ProgressBar extends React.Component {
constructor (props) {
super(props);
this.state = {
bars : [],
index : 0,
incrementer: 1,
};
this.createBars = this.createBars.bind(this);
2018-01-12 02:38:01 +01:00
this.startProgressBar = this.startProgressBar.bind(this);
this.updateProgressBar = this.updateProgressBar.bind(this);
this.stopProgressBar = this.stopProgressBar.bind(this);
}
componentDidMount () {
this.createBars();
this.startProgressBar();
2018-01-12 02:38:01 +01:00
}
componentWillUnmount () {
this.stopProgressBar();
}
createBars () {
const bars = [];
for (let i = 0; i <= this.props.size; i++) {
bars.push({isActive: false});
}
this.setState({ bars });
2018-01-12 02:38:01 +01:00
}
startProgressBar () {
this.updateInterval = setInterval(this.updateProgressBar.bind(this), 300);
};
updateProgressBar () {
let index = this.state.index;
let incrementer = this.state.incrementer;
let bars = this.state.bars;
// flip incrementer if necessary, to stay in bounds
if ((index < 0) || (index > this.props.size)) {
2018-01-12 02:38:01 +01:00
incrementer = incrementer * -1;
index += incrementer;
}
// update the indexed bar
2018-01-12 02:38:01 +01:00
if (incrementer > 0) {
bars[index].isActive = true;
2018-01-12 02:38:01 +01:00
} else {
bars[index].isActive = false;
2018-01-12 02:38:01 +01:00
};
// increment index
index += incrementer;
// update state
this.setState({
bars,
incrementer,
index,
});
};
stopProgressBar () {
clearInterval(this.updateInterval);
};
render () {
return (
<div>
{this.state.bars.map((bar, index) => bar.isActive ? <ActiveStatusBar key={index} /> : <InactiveStatusBar key={index}/>)}
2018-01-12 02:38:01 +01:00
</div>
);
}
};
ProgressBar.propTypes = {
size: PropTypes.number.isRequired,
};
2018-01-12 02:38:01 +01:00
export default ProgressBar;