Skip to content

Executing a loop in React class component

I’m building a pagination component and I’m struggling to execute a for loop so I can dynamically generate the pages. I initially had a function component, but I want to switch it to a class component so I can manage state in it. (I know, I can use hooks, but Im practicing class components at the moment).

I initially added the for loop in the render method but it is executing the loop twice because the component ir rendering twice. Then, I tried componentDidMount() but it doesn’t do anything… then used componentWillMount() and it worked. However, I know this could be bad practice.

Any ideas? See below the component with componentDidMount()

import React, { Component } from 'react';
import styles from './Pagination.module.css';

class Pagination extends Component {
    state = {
        pageNumbers: [],
        selected: '',

    componentDidMount() {
        for (
            let i = 1;
            i <= Math.ceil(this.props.totalDogs / this.props.dogsPerPage);
        ) {

    classActiveForPagineHandler = (number) => {
        this.setState({ selected: number });

    render() {
        return (
            <div className={styles.PaginationContainer}>
                    <ul className={styles.PageListHolder}>
                        { => (
                            <li key={num}>
                                        this.state.selected === num
                                            ? styles.Active
                                            : styles.PageActive
                                    onClick={() => {
                                        // this.props.classActiveForPagineHandler(num);

export default Pagination;



You better push all the numbers into array and then update pageNumbers state. this.state.pageNumbers.push(i); does not update state directly, you need use setState after your calculation completes.

 componentDidMount() {
  const { pageNumbers = [] } = this.state
  const { totalDogs, dogsPerPage } = this.props
  for (let i = 1; i <= Math.ceil(totalDogs / dogsPerPage); i++) {

  this.setState({ pageNumbers })

Demo link here

User contributions licensed under: CC BY-SA
7 People found this is helpful