I want to achieve working pagination tabs something like this.
I have an application which fetches news from newapi.org and displaying on screen.
My News Page looks like this
import React, { Component } from 'react'
import NewsItem from '../components/NewsItem';
import { Col, Row, Stack } from 'react-bootstrap';
import PageTabs from './PageTabs';
export default class News extends Component {
constructor(){
super();
this.state = {articles:[],currentPage:0,loading:true};
}
async componentDidMount(){
let url = process.env.REACT_APP_BASE_URL_EVERYTHING;
let data = await fetch(url);
let parsedData = await data.json();
this.setState(
{ articles:parsedData.articles.filter((elem)=>elem.title!='[Removed]' && elem.urlToImage!=null),
currentPage:1,
totalPage: Math.ceil(parsedData.totalResults/100),
loading:false}
);
}
render() {
const onPageChange = (num)=>{
if(num != this.state.currentPage){
this.setState({
...this.state,
currentPage:num
});
}
}
return (
<>
{
this.state.loading?<div className="spinner-border" role="status">
<span className="visually-hidden">Loading...</span>
</div> :
<Stack>
<Row>
{this.state.articles.map((elem)=>{
return (
<Col md={6} lg={4} key={elem.title} >
<NewsItem title={elem.title} description={elem.description} url={elem.url} image={elem.urlToImage}/>
</Col>
);
})}
</Row>
<PageTabs totalPages={this.state.totalPage} currentIndex={this.state.currentPage} onTabClick={onPageChange}/>
</Stack>
}
</>
)
}
}
It holds the news item and below that is the pagination tabs.
The PageTabs component looks like this
import React, { Component } from 'react'
import { Pagination } from 'react-bootstrap';
export default class PageTabs extends Component {
constructor(){
super();
this.state = {
startIndex : 0
}
}
render() {
let {totalPages, activeIndex , onTabClick} = this.props;
console.log('Total page ',totalPages);
console.log('Curent ',activeIndex);
console.log('Funct ',onTabClick);
// Needs to be sliced
let items = [];
for (let number = 1; number <= totalPages; number++) {
items.push(
<Pagination.Item
key={number}
active={number === activeIndex}
onClick={onTabClick(number)}>
{number}
</Pagination.Item>
);
}
let tabsToShow = items.slice(this.state.startIndex , this.state.startIndex+10);
return (
<Pagination>
<Pagination.First onClick={()=>{ this.setState({startIndex : 0}) }}/>
<Pagination.Prev onClick={()=>{ this.setState({startIndex : this.state.startIndex-10}) }}/>
<Pagination.Ellipsis />
{tabsToShow}
<Pagination.Ellipsis />
<Pagination.Next onClick={()=>{ this.setState({startIndex : this.state.startIndex+10}) }}/>
<Pagination.Last onClick={()=>{ this.setState({startIndex : totalPages-10}) }}/>
</Pagination>
)
}
}
The issue is when I start the server the render method gets called infinitely as the console gets flooded with the logs provided in the render method of PageTabs component.
What is the exact issue?