Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React render multiple buttons in for loop from given integer

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. enter image description here

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?


1 Answers

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>);
like image 107
ibrahim mahrir Avatar answered Nov 08 '25 10:11

ibrahim mahrir