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); i++ ) { this.state.pageNumbers.push(i); } } classActiveForPagineHandler = (number) => { this.setState({ selected: number }); }; render() { return ( <div className={styles.PaginationContainer}> <nav> <ul className={styles.PageListHolder}> {this.state.pageNumbers.map((num) => ( <li key={num}> <a href="!#" className={ this.state.selected === num ? styles.Active : styles.PageActive } onClick={() => { this.props.paginate(num); // this.props.classActiveForPagineHandler(num); }} > {num} </a> </li> ))} </ul> </nav> </div> ); } } export default Pagination;
Advertisement
Answer
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++) { pageNumbers.push(i); } this.setState({ pageNumbers }) }
Demo link here