Created
March 6, 2019 11:09
-
-
Save agoiabel/3ba68a0f1fe6ca6f21082c0fca37bed2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import styles from './App.module.css'; | |
class App extends Component { | |
state = { | |
users: null, | |
total: null, | |
per_page: null, | |
current_page: 1 | |
} | |
componentDidMount() { | |
this.makeHttpRequestWithPage(1); | |
} | |
makeHttpRequestWithPage = async pageNumber => { | |
const response = await fetch(`https://reqres.in/api/users?page=${pageNumber}`, { | |
method: 'GET', | |
headers: { | |
'Accept': 'application/json', | |
'Content-Type': 'application/json', | |
}, | |
}); | |
const data = await response.json(); | |
this.setState({ | |
users: data.data, | |
total: data.total, | |
per_page: data.per_page, | |
current_page: data.page | |
}); | |
} | |
render() { | |
let users, renderPageNumbers; | |
if (this.state.users !== null) { | |
users = this.state.users.map(user => ( | |
<tr key={user.id}> | |
<td>{user.id}</td> | |
<td>{user.first_name}</td> | |
<td>{user.last_name}</td> | |
</tr> | |
)); | |
} | |
const pageNumbers = []; | |
if (this.state.total !== null) { | |
for (let i = 1; i <= Math.ceil(this.state.total / this.state.per_page); i++) { | |
pageNumbers.push(i); | |
} | |
renderPageNumbers = pageNumbers.map(number => { | |
let classes = this.state.current_page === number ? styles.active : ''; | |
return ( | |
<span key={number} className={classes} onClick={() => this.makeHttpRequestWithPage(number)}>{number}</span> | |
); | |
}); | |
} | |
return ( | |
<div className={styles.app}> | |
<table className={styles.table}> | |
<thead> | |
<tr> | |
<th>S/N</th> | |
<th>First Name</th> | |
<th>Last Name</th> | |
</tr> | |
</thead> | |
<tbody> | |
{users} | |
</tbody> | |
</table> | |
<div className={styles.pagination}> | |
<span onClick={() => this.makeHttpRequestWithPage(1)}>«</span> | |
{renderPageNumbers} | |
<span onClick={() => this.makeHttpRequestWithPage(1)}>»</span> | |
</div> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment