The answer by Orlyyn explains it well. Just adding to it:
- You can probably destructure your variables, this helps with readability and reuse.
- Since you are not using the state of the class you can convert that into
Functional Component - Use
template stringinstead of doing it in bits. - Still no need to add
this.stateand callsetStatein yourcomponentDidMount(). What heOrlyyn meant by single responsibility principle was that there shouldn't be any other logic in there, simply. You can still get the variables that you need for that function to work.
The State is useful when you need to manipulate it within your very class or function.
So, a refactor of your code batch_progress.js could be as following:
import React from 'react';
import PropTypes from 'prop-types';
import ProgressBar from '../progress_bar/progress_bar';
const statusCodeColors = {
100: '#e7e4f1',
200: '#c3dcec',
300: '#ecc6eb',
400: '#ecdec3',
500: '#c8ecc7',
};
const getStatusColor = (code) => statusCodeColors[code] || '#e7e4f1';
const getPercentage = (num, total) => (num / total) * 100;
const BatchStatus = ({ batch: { number, status }, targetBatchCount }) => {
const color = getStatusColor(status);
const percentage = getPercentage(number, targetBatchCount);
return (
<ProgressBar foregroundColor={color} percentage={percentage}>
{`${number} / ${targetBatchCount}`}
</ProgressBar>
);
};
BatchStatus.defaultProps = {
batch: {
number: 50,
status: 100,
},
targetBatchCount: 100,
};
BatchStatus.propTypes = {
batch: PropTypes.shape({
number: PropTypes.number,
status: PropTypes.number,
}),
targetBatchCount: PropTypes.number,
};
export default BatchStatus;
Included the prop-types there. Might help you in getting started with it. Though react has a great documentation for it.
I have also replaced your switch-case statement there with something more cleaner. You can read about it in following articles: