I am slowly digesting React.js, found couple of ways to write the same piece of code: Please tell where all I went wrong in below code.
- I try to put logic inside
render()
, is that Ok? - Not using React life cycles for simple components?
- Use Functional components instead of class components?
File 1: batch_progress.js
Description: Shows batch progress, expects 3 values:
- current batch.
- target batch count.
- state of the batch (based on which the progress bar color changes).
import React, { Component } from 'react'; import ProgressBar from '../progress_bar/progress_bar'; export default class BatchStatus extends Component { constructor(props) { super(props); } render() { let color; let percentage = (this.props.batch.number / this.props.targetBatchCount) * 100; switch (this.props.batch.status) { case 100: color = '#e7e4f1'; break; case 200: color = '#c3dcec'; break; case 300: color = '#ecc6eb'; break; case 400: color = '#ecdec3'; break; case 500: color = '#c8ecc7'; break; default: color = '#e7e4f1'; } return ( <ProgressBar foregroundColor={color} percentage={percentage}> {this.props.batch.number} / {this.props.targetBatchCount} </ProgressBar> ); } }
File 2: progress_bar.js
import React, { Component } from 'react'; import './progress_bar.css'; export default class ProgressBar extends Component { constructor(props) { super(props); } render() { let foregroundColor = this.props.foregroundColor || '#e7e4f1'; let percentage = this.props.percentage || 0; let backgroundColor = this.props.backgroundColor || '#eceeef'; let style = { backgroundImage: 'linear-gradient(to right, ' + foregroundColor + ' ' + percentage + '%, ' + backgroundColor + ' 0%)' }; return ( <div className="progress-bar-container" style={style}> {this.props.children} </div> ); } }