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[edit]

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

git clone pagination-cmp
git remote rm origin
yarn && yarn start

Component Paging with StencilJS[edit]

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

components /

 pagination / 

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 {
  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;

  tag: 'pagination',
  styleUrl: 'pagination.css'
export class MyFetch {

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

  componentWillLoad() {

  _fetchUsers (page = 1) {
      .then(response => response.json())
      .then(json => {
        this.users =;
        this.pages = json.total_pages; =;

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

  changePage (page) {

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

        <ul class="fetch-pagination">

About This Tutorial

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