I am building a progress bar which takes two inputs, totalSteps and activeStep. I am going to render a number of circles equal to the number of total steps, with the active step being grey.

I have experience mapping over an array of objects however in this case I don't have an array I am just given an integer.
I am attempting to write a function which returns a div in a for loop but this isn't working.
const ProgressBar = (props) => {
const { activeStep, totalSteps } = props;
const displayProgressBar = () => {
for (let i = 1; i <= totalSteps; i++) {
return <div>Hello</div>;
}
};
return <div className="progressBar">{displayProgressBar()}</div>;
};
The above code only renders Hello once even if totalSteps is 3. Is there a way to achieve the desired results without creating an array?
Your for loop terminates after the first iteration because return terminates the function call immediately. You need to accumulate the JSX elements in an array and use that instead. You also don't need the function displayProgressBar at all.
const ProgressBar = (props) => {
const { activeStep, totalSteps } = props;
const steps = [];
for (let i = 1; i <= totalSteps; i++) {
steps.push(<div>Hello</div>);
}
return (<div className="progressBar">{ steps }</div>);
};
You should probably add an active class or something to the activeStep item so it is selected, change steps.push(...) from above to:
steps.push(<div className={ i == activeStep ? "active" : "" }>Hello</div>);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With