How to Do Pagination with Stenciljs

From WikiHTP

In this tutorial, we will see how easy it is to develop a Pagination with StencilJS in a simple way with a single component ready to reuse in Angular, Vue or ReactJS.

Generating a project with StencilJS

To generate a new project we will use the starter that we offer from GitHub with the following command.

git clone https://github.com/ionic-team/stencil-app-starter pagination-cmp
git remote rm origin
yarn && yarn start

Component Paging with StencilJS

Now we must create a new component with StencilJS, for that, we will create the following structure within our components directory.

components /

 pagination / 
   pagination.tsx 
   pagination.css

The first thing we must do is open the CSS file to add some styles that we will use for our paging.

#fetch {
  text-align: center;
  margin: 20px;
}

.fetch-user {
  background-color: lightseagreen;
  color: #fff;
  padding: 10px;
  margin-bottom: 5px;
}

.fetch-pagination li {
  list-style-type: none;
  float: left;
  background-color: lightseagreen;
  color: #fff;
  padding: 10px;
  margin-right: 5px;
  cursor: pointer;
}

.fetch-pagination li.active {
  background-color: #333333;
  color: #fff;
}

Finally, we just have to add the .tsx code so that our component starts to work.

import {Component, State} from '@stencil/core';

interface User {
  id: number;
  first_name: string;
  last_name: string;
}

@Component({
  tag: 'pagination',
  styleUrl: 'pagination.css'
})
export class MyFetch {

  @State() users: User[] = [];
  @State() pages: number;
  @State() page: number = 1;

  componentWillLoad() {
    this._fetchUsers()
  }

  _fetchUsers (page = 1) {
    fetch(`https://reqres.in/api/users?page=${page}`)
      .then(response => response.json())
      .then(json => {
        this.users = json.data;
        this.pages = json.total_pages;
        this.page = json.page;
      })
  }

  pagination () {
    let pages = [];
    for(let i = 1; i <= this.pages; i ++) {
      if(i === this.page) {
        pages.push(<li class="active">{i}</li>)
      } else {
        pages.push(<li onClick={() => this.changePage(i)}>{i}</li>)
      }
    }
    return pages;
  }

  changePage (page) {
    this._fetchUsers(page);
  }

  render () {
    return (
      <div id="fetch">
        {this.users.map((user: User) =>
          <div class="fetch-user">
            ID: {user.id}, Nombre: {user.first_name}, Apellido: {user.last_name}
          </div>
        )}

        <ul class="fetch-pagination">
          {this.pagination()}
        </ul>
      </div>
    )
  }
}

About This Tutorial

This page was last edited on 14 February 2019, at 21:33.