I have created a custom pagination in React: I basically have in the container pagination which will be visible only when data is received:
...
{this.state.displayTweets.length != 0 && <Pagination pageCount={this.state.pageCount} pagination={this.pagination.bind(this)}/>}
...
This is the function that is called when a pagination item is clicked:
pagination(data){
if(data == -1 && offset>0){
console.log("Previous")
offset -= perPage
this.setState({displayTweets: this.state.tweets.slice(offset,offset+perPage)})
} else if(data == 0 && pageNumber < this.state.pageCount) {
console.log("Next")
pageNumber += 1
offset += perPage
this.setState({displayTweets: this.state.tweets.slice(offset,offset+perPage)});
} else if(data > 0 && data < this.state.pageCount){
console.log("Between")
pageNumber = data
offset = perPage*(data-1)
this.setState({displayTweets: this.state.tweets.slice(offset,perPage*data)});
}
console.log("Page number: "+pageNumber)
console.log("Offset: "+offset)
}
And here is the actual Pagination component:
import React from 'react';
const PageLi = (props) => {
let pages = [];
for (let i = 1; i <= props.pageCount; i++) {
pages.push(<li className="page-item" onClick={() => { props.pagination(i)}} key={i}><a className="page-link">{i}</a></li>);
}
return (
<nav aria-label="Page navigation example">
<ul className="pagination">
<li className="page-item" onClick={() => { props.pagination(-1)}}><a className="page-link">Previous</a></li>
{pages}
<li className="page-item"><a onClick={() => { props.pagination(0)}} className="page-link">Next</a></li>
</ul>
</nav>
);
};
export default PageLi;
Everything works as expected. Now I would like that when I click on a pagination item to change the class from page-item' to 'page-item-active' and remove the
active part` from the previously clicked one. How can I do this in React? I know that I can set states, but to have a state for each page number would be stupid.
via Bogdan Daniel
No comments:
Post a Comment