I have a basic components with working pagination displaying props in a table.
This however shows all the page numbers which is not ideal I would like only a few to be seen.
e.g 1-2-3-4-5-20 so that it does not take up too much space.
This is the component itself.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
class AllAlerts extends Component {
state = {
currentPage: 1,
alertsPerPage: 8,
};
componentDidMount() {}
handleClick(number) {
this.setState({
currentPage: number,
});
}
render() {
// Logic for displaying alerts
const { currentPage, alertsPerPage } = this.state;
const indexOfLastAlerts = currentPage * alertsPerPage;
const indexOfFirstAlerts = indexOfLastAlerts - alertsPerPage;
const currentAlerts = this.props.alerts.slice(indexOfFirstAlerts, indexOfLastAlerts);
const renderAlerts = currentAlerts.map((alerts, index) => {
return (
<li key={index}>
<div>
All Title {alerts.title}
<li>All ID {alerts.id}</li>
<li>All user Id {alerts.userId}</li>
</div>
</li>
);
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(this.props.alerts.length / alertsPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map((number) => {
return (
<button key={number} id={number} onClick={() => this.handleClick(number)}>
{number}
</button>
);
});
return (
<>
<>All Alerts</>
<br />
<form class="example" action="/action_page.php">
<input type="text" placeholder="Search.." name="search" />
<button type="submit">
<i class="fa fa-search"></i>
</button>
</form>
<>{renderAlerts}</>
<>{renderPageNumbers}</>
</>
);
}
}
export default AllAlerts;
From my understanding I would change this in this part of the code.
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(this.props.alerts.length / alertsPerPage); i++) {
pageNumbers.push(i);
//Only push 1-5 and last which has to change depending on page number
}
I have tried a few different approaches all not achieving what I would like.
Thank you for your help :)