Tag: Component

Creating a Reusable Pagination Component in Vue

The idea behind most of web applications is to fetch data from the database and present it to the user in the best possible way. When we deal with data there are cases when the best possible way of presentation means creating a list.

Depending on the amount of data and its content, we may decide to show all content at once (very rarely), or show only a specific part of a bigger data set (more likely). The main reason behind showing only part of the existing data is that we want to keep our applications as performant as possible and avoid loading or showing unnecessary data.

If we decide to show our data in “chunks” then we need a way to navigate through that collection. The two most common ways of navigating through set of data are:

The first is pagination, a technique that splits the set of data into a specific number of pages, saving users from being overwhelmed by the amount of data on one page and allowing them to view one set of results at a time. Take this very blog you’re reading, for example. The homepage lists the latest 10 posts. Viewing the next set of latest posts requires clicking a button.

The second common technique is infinite scrolling, something you’re likely familiar with if you’ve ever scrolled through a timeline on either Facebook or Twitter.

The Apple News app also uses infinite scroll to browse a list of articles.

We’re going to take a deeper look at the first type in this post. Pagination is something we encounter on a near-daily basis, yet making it is not exactly trivial. It’s a great use case for a component, so that’s exactly what we’re going to do. We will go through the process of creating a component that is in charge of displaying that list, and triggering the action that fetches additional articles when we click on a specific page to be displayed. In other words, we’re making a pagination component in Vue.js like this:

Let’s go through the steps together.

Step 1: Create the ArticlesList component in Vue

Let’s start by creating a component that will show a list of articles (but without pagination just yet). We’ll call it ArticlesList. In the component template, we’ll iterate through the set of articles and pass a single article item to each ArticleItem component.

// ArticlesList.vue <template>   <div>     <ArticleItem       v-for="article in articles"       :key="article.publishedAt"       :article="article"     />   </div> </template>

In the script section of the component, we set initial data:

  • articles: This is an empty array filled with data fetched from the API on mounted hook.
  • currentPage: This is used to manipulate the pagination.
  • pageCount : This is the total number of pages, calculated on mounted hook based on the API response.
  • visibleItemsPerPageCount: This is how many articles we want to see on a single page.

At this stage, we fetch only first page of the article list. This will give us a list two articles:

// ArticlesList.vue import ArticleItem from "./ArticleItem" import axios from "axios" export default {   name: "ArticlesList",   static: {     visibleItemsPerPageCount: 2   },   data() {     return {       articles: [],       currentPage: 1,       pageCount: 0     }   },   components: {      ArticleItem,    },   async mounted() {     try {       const { data } = await axios.get(         `?country=us&page=1&pageSize=$ {           this.$ options.static.visibleItemsPerPageCount         }&category=business&apiKey=065703927c66462286554ada16a686a1`       )       this.articles = data.articles       this.pageCount = Math.ceil(         data.totalResults / this.$ options.static.visibleItemsPerPageCount       )     } catch (error) {       throw error     }   } }

Step 2: Create pageChangeHandle method

Now we need to create a method that will load the next page, the previous page or a selected page.

In the pageChangeHandle method, before loading new articles, we change the currentPage value depending on a property passed to the method and fetch the data respective to a specific page from the API. Upon receiving new data, we replace the existing articles array with the fresh data containing a new page of articles.

// ArticlesList.vue ... export default { ...   methods: {     async pageChangeHandle(value) {       switch (value) {         case 'next':           this.currentPage += 1           break         case 'previous':           this.currentPage -= 1           break         default:           this.currentPage = value       }       const { data } = await axios.get(         `?country=us&page=$ {this.currentPage}&pageSize=$ {           this.$ options.static.visibleItemsPerPageCount         }&category=business&apiKey=065703927c66462286554ada16a686a1`       )       this.articles = data.articles     }   } }

Step 3: Create a component to fire page changes

We have the pageChangeHandle method, but we do not fire it anywhere. We need to create a component that will be responsible for that.

This component should do the following things:

  1. Allow the user to go to the next/previous page.
  2. Allow the user to go to a specific page within a range from currently selected page.
  3. Change the range of page numbers based on the current page.

If we were to sketch that out, it would look something like this:

Let’s proceed!

Requirement 1: Allow the user to go to the next or previous page

Our BasePagination will contain two buttons responsible for going to the next and previous page.

// BasePagination.vue <template>   <div class="base-pagination">     <BaseButton       :disabled="isPreviousButtonDisabled"       @click.native="previousPage"     >       ←     </BaseButton>     <BaseButton       :disabled="isNextButtonDisabled"       @click.native="nextPage"     >       →     </BaseButton>   </div> </template>

The component will accept currentPage and pageCount properties from the parent component and emit proper actions back to the parent when the next or previous button is clicked. It will also be responsible for disabling buttons when we are on the first or last page to prevent moving out of the existing collection.

// BasePagination.vue import BaseButton from "./BaseButton.vue"; export default {   components: {     BaseButton   },   props: {     currentPage: {       type: Number,       required: true     },     pageCount: {       type: Number,       required: true     }   },   computed: {     isPreviousButtonDisabled() {       return this.currentPage === 1     },     isNextButtonDisabled() {       return this.currentPage === this.pageCount     }   },   methods: {     nextPage() {       this.$ emit('nextPage')     },     previousPage() {       this.$ emit('previousPage')     }   }

We will render that component just below our ArticleItems in ArticlesList component.

// ArticlesList.vue <template>   <div>     <ArticleItem       v-for="article in articles"       :key="article.publishedAt"       :article="article"     />     <BasePagination       :current-page="currentPage"       :page-count="pageCount"       class="articles-list__pagination"       @nextPage="pageChangeHandle('next')"       @previousPage="pageChangeHandle('previous')"     />   </div> </template>

That was the easy part. Now we need to create a list of page numbers, each allowing us to select a specific page. The number of pages should be customizable and we also need to make sure not to show any pages that may lead us beyond the collection range.

Requirement 2: Allow the user to go to a specific page within a range

Let’s start by creating a component that will be used as a single page number. I called it BasePaginationTrigger. It will do two things: show the page number passed from the BasePagination component and emit an event when the user clicks on a specific number.

// BasePaginationTrigger.vue <template>   <span class="base-pagination-trigger" @click="onClick">     {{ pageNumber }}   </span> </template> <script> export default {   props: {     pageNumber: {       type: Number,       required: true     }   },   methods: {     onClick() {       this.$ emit("loadPage", this.pageNumber)     }   } } </script>

This component will then be rendered in the BasePagination component between the next and previous buttons.

// BasePagination.vue <template>   <div class="base-pagination">     <BaseButton />     ...     <BasePaginationTrigger       class="base-pagination__description"       :pageNumber="currentPage"       @loadPage="onLoadPage"     />     ...     <BaseButton />   </div> </template>

In the script section, we need to add one more method (onLoadPage) that will be fired when the loadPage event is emitted from the trigger component. This method will receive a page number that was clicked and emit the event up to the ArticlesList component.

// BasePagination.vue export default {   ...     methods: {     ...     onLoadPage(value) {       this.$ emit("loadPage", value)     }   } }

Then, in the ArticlesList, we will listen for that event and trigger the pageChangeHandle method that will fetch the data for our new page.

// ArticlesList <template>   ...     <BasePagination       :current-page="currentPage"       :page-count="pageCount"       class="articles-list__pagination"       @nextPage="pageChangeHandle('next')"       @previousPage="pageChangeHandle('previous')"       @loadPage="pageChangeHandle"     />   ... </template>

Requirement 3: Change the range of page numbers based on the current page

OK, now we have a single trigger that shows us the current page and allows us to fetch the same page again. Pretty useless, don’t you think? Let’s make some use of that newly created trigger component. We need a list of pages that will allow us to jump from one page to another without needing to go through the pages in between.

We also need to make sure to display the pages in a nice manner. We always want to display the first page (on the far left) and the last page (on the far right) on the pagination list and then the remaining pages between them.

We have three possible scenarios:

  1. The selected page number is smaller than half of the list width (e.g. 1 – 2 – 3 – 4 – 18)
  2. The selected page number is bigger than half of the list width counting from the end of the list (e.g. 1 – 15 – 16 – 17 – 18)
  3. All other cases (e.g. 1 – 4 – 5 – 6 – 18)

To handle these cases, we will create a computed property that will return an array of numbers that should be shown between the next and previous buttons. To make the component more reusable we will accept a property visiblePagesCount that will specify how many pages should be visible in the pagination component.

Before going to the cases one by one we create few variables:

  • visiblePagesThreshold:- Tells us how many pages from the centre (selected page should be shown)
  • paginationTriggersArray: Array that will be filled with page numbers
  • visiblePagesCount: Creates an array with the required length
// BasePagination.vue export default {   props: {     visiblePagesCount: {       type: Number,       default: 5     }   }   ...   computed: {     ...       paginationTriggers() {         const currentPage = this.currentPage         const pageCount = this.pageCount         const visiblePagesCount = this.visiblePagesCount         const visiblePagesThreshold = (visiblePagesCount - 1) / 2         const pagintationTriggersArray = Array(this.visiblePagesCount - 1).fill(0)       }     ...     }   ... }

Now let’s go through each scenario.

Scenario 1: The selected page number is smaller than half of the list width

We set the first element to always be equal to 1. Then we iterate through the list, adding an index to each element. At the end, we add the last value and set it to be equal to the last page number — we want to be able to go straight to the last page if we need to.

if (currentPage <= visiblePagesThreshold + 1) {   pagintationTriggersArray[0] = 1   const pagintationTriggers = pagintationTriggersArray.map(     (paginationTrigger, index) => {       return pagintationTriggersArray[0] + index     }   )   pagintationTriggers.push(pageCount)   return pagintationTriggers }
Scenario 2: The selected page number is bigger than half of the list width counting from the end of the list

Similar to the previous scenario, we start with the last page and iterate through the list, this time subtracting the index from each element. Then we reverse the array to get the proper order and push 1 into the first place in our array.

if (currentPage >= pageCount - visiblePagesThreshold + 1) {   const pagintationTriggers = pagintationTriggersArray.map(     (paginationTrigger, index) => {       return pageCount - index     }   )   pagintationTriggers.reverse().unshift(1)   return pagintationTriggers }
Scenario 3: All other cases

We know what number should be in the center of our list: the current page. We also know how long the list should be. This allows us to get the first number in our array. Then we populate the list by adding an index to each element. At the end, we push 1 into the first place in our array and replace the last number with our last page number.

pagintationTriggersArray[0] = currentPage - visiblePagesThreshold + 1 const pagintationTriggers = pagintationTriggersArray.map(   (paginationTrigger, index) => {     return pagintationTriggersArray[0] + index   } ) pagintationTriggers.unshift(1); pagintationTriggers[pagintationTriggers.length - 1] = pageCount return pagintationTriggers

That covers all of our scenarios! We only have one more step to go.

Step 5: Render the list of numbers in BasePagination component

Now that we know exactly what number we want to show in our pagination, we need to render a trigger component for each one of them.

We do that using a v-for directive. Let’s also add a conditional class that will handle selecting our current page.

// BasePagination.vue <template>   ...   <BasePaginationTrigger     v-for="paginationTrigger in paginationTriggers"     :class="{       'base-pagination__description--current':         paginationTrigger === currentPage     }"     :key="paginationTrigger"     :pageNumber="paginationTrigger"     class="base-pagination__description"     @loadPage="onLoadPage"   />   ... </template>

And we are done! We just built a nice and reusable pagination component in Vue.

When to avoid this pattern

Although this component is pretty sweet, it’s not a silver bullet for all use cases involving pagination.

For example, it’s probably a good idea to avoid this pattern for content that streams constantly and has a relatively flat structure, like each item is at the same level of hierarchy and has a similar chance of being interesting to the user. In other words, something less like an article with multiple pages and something more like main navigation.

Another example would be browsing news rather than looking for a specific news article. We do not need to know where exactly the news is and how much we scrolled to get to a specific article.

That’s a wrap!

Hopefully this is a pattern you will be able to find useful in a project, whether it’s for a simple blog, a complex e-commerce site, or something in between. Pagination can be a pain, but having a modular pattern that not only can be re-used, but considers a slew of scenarios, can make it much easier to handle.

The post Creating a Reusable Pagination Component in Vue appeared first on CSS-Tricks.

CSS-Tricks

, , ,

Styling a Web Component

This confused me for a bit here so I’m writing it out while it’s fresh in mind. Just because you’re using a web component doesn’t mean the styles of it are entirely isolated. You might have content within a web component that is styled normally along with the rest of your website. Like this:

See the Pen yGaNKr by Chris Coyier (@chriscoyier) on CodePen.

That <whats-up> element isolated the JavaScript-powered functionality of itself by attaching a click handler to the <button> inside of it. But the styling of that button comes from global CSS applied to that page.

But let’s say we move that <button> into the web component, so we can use <whats-up> all by itself. We could do that by .innerHTML‘ing the web component (I suppose because it’s really a “custom element”):

See the Pen Web Component with Global Styles (because no Shadow DOM) by Chris Coyier (@chriscoyier) on CodePen.

Again, entirely styled by the global CSS. Cool. That may be desirable. It also might not be desirable. Perhaps you’re looking to web components to isolate styles for you. Web components can do that via the Shadow DOM. Here’s that same component, using Shadow DOM instead:

See the Pen Web Component with Local Styles by Chris Coyier (@chriscoyier) on CodePen.

Note that the functionality still works (although we had to querySelector<code> through the <code>shadowRoot), but we’ve totally lost the global styling. The Shadow DOM boundry (shadow root) prevents styling coming in or going out (sorta like an iframe).

Shadow Root

There is no global way to penetrate that boundary that I’m aware of, so if you want to bring styles in, you gotta bring them into the template.

See the Pen Web Component with Local Styles by Chris Coyier (@chriscoyier) on CodePen.

This would be highly obnoxious if you both really wanted to use the Shadow DOM but also wanted your global styles. It’s funny that there is a Shadow DOM “mode” for open and closed for allowing or disallowing JavaScript in and out, but not CSS.

If that’s you, you’ll probably need to @import whatever global stylesheets you can to bring in those global styles and hope they are cached and the browser is smart about it in such a way that it isn’t a big performance hit.

I’ll use CodePen’s direct link to CSS feature to import the styles from the Pen itself into the web component:

See the Pen Web Component with Local Styles by Chris Coyier (@chriscoyier) on CodePen.

Another important thing to know is that CSS custom properties penetrate the Shadow DOM! That’s right, they do. You can select the web component in the CSS and set them there:

See the Pen Web Component with Custom Properties by Chris Coyier (@chriscoyier) on CodePen.

The post Styling a Web Component appeared first on CSS-Tricks.

CSS-Tricks

,
[Top]

Fun Tip: Use calc() to Change the Height of a Hero Component

The concept of Fluid Typography was tossed around a couple of years ago. The main idea is that if you know what size your font is at two different viewport sizes, then you can have the font scaling smoothly between the two sizes. We had a jQuery solution for this in FitText (meant of headings, of course) until the calc() function was shipped giving us a pure CSS solution.

p {   font-size: calc(16px + (24 - 16)*(100vw - 400px)/(800 - 400)); }

See the Pen Fluid Typography by Martino Stenta (@martinostenta) on CodePen.

The important numbers here are 24px (the larger font up to 800px viewports) and 16px (the smaller font size down to 400px viewports). I wouldn’t use the terms “minimum” or “maximum” to describe font sizes and viewports in this context because it is a little misleading. In fact, you still need to provide a default font size for viewports smaller than 400px and bigger than 800px — otherwise, the font will keep getting smaller (or bigger) with the same scale of the equation. Or, if you are fancy, you could define another scale for bigger screen sizes.

See the Pen Fluid Typography with reset size by Martino Stenta (@martinostenta) on CodePen.

It works really well and you should definitely check the math behind this.

Padding and line height?

I liked the concept of Fluid Typography so much that I asked myself if it could work with other properties. And it does! You can’t use a percentage, but as long as you stick with px, em or rem units, then it’s OK. I’m a pixel guy, so all my experiments have used those, but there is this neat generatorthat helps you with conversions if you need it.

So, back to padding and line-height. Using the same calc() logic, we can achieve a fully fluid *layout* with fixed values for defined screen sizes.

See the Pen Pure CSS Variable Padding, Font Size and Line Height by Martino Stenta (@martinostenta) on CodePen.

I implemented this idea on this website, but kept it to font-size and line-height. And, yes, it gets easier to look past all that math and put to use the more you work with it.

See the Pen Working Example of calc() on font-size and line-hieght by Martino Stenta (@martinostenta) on CodePen.

A digression about “Hero” components

If you’re like me, then you might take issue with what we all have come to know as the hero component. It’s ubiquitous to the extent that it’s become a staple in design systems (like Bootstrap) and you may have even seen it satirized on sites like this.

My main gripe concerns the best way to make them responsive. If it’s not a *full screen* hero (i.e. takes over the entire viewport at any size), then I usually ask the designer how the page should behave. There’s often a proportion of the hero page that works fine, so that allows me to use padding-bottom in % with absolute positioning of the inner content. That tactic works most of the time,

This is fun and it works fine especially on the desktop version of a website. You end up with a neat hero section, the proportion is good and the content is centered.

See the Pen Standard hero section with ‘padding-bottom’ by Martino Stenta (@martinostenta) on CodePen.

But what happens when you start shrinking the viewport? The hero remains readable up to a point, you really need to change the proportion.

Assuming we are working with a desktop-first responsive approach, we could start with a horizontal rectangle that scales down to the point where we’re left with a vertical rectangle on small screens.

Hero component with different proportions based on device

This is a PITA because you could end up with many lines of CSS to have a nice and readable hero section at various breakpoints.

There has to be a better way, right? What if the hero could increase its height while the page width gets narrower?

Back to fluidity!

So, I turned back to the calc() function that worked in those other situations, like making the browser handle the math and scale things accordingly as the viewport changes.

Here’s the CSS from the Fluid Typography example we started with:

p {   width: 100%;   max-width: 1200px;   margin: 0 auto;   font-family: 'Open Sans', sans-serif;   font-size: calc(24px + (18 - 24)*(100vw - 400px)/(1200 - 400));   line-height: 1.5;   padding: 10px; }

Here’s what we want: a hero component that gets bigger while you shrink the page. I used pixel units for the fluid part and percentages everywhere else.

Here’s a screencast of how the solution I landed on:

Live Demo

This is pretty useful when you want to give more vertical space to the text. Shrinking the viewport width from large to small will end up having more lines for the same text, since the font size can’t be too small.

See the Pen Hero section with calc() by Martino Stenta (@martinostenta) on CodePen.

Pretty nice, right? Yet another way calc() proved it could solve a scenario for me.

Yes, there are some caveats

Browser support is very good, tallying almost 93% of the users (at the time of writing), with the main exception being Opera mini.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Opera Firefox IE Edge Safari
19* 15 4* 10 12 6*

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
6.0-6.1* 46 No 67 69 62

Also, remember that this calc() technique supports only px, em, and rem units. But the examples we covered here are pretty easy to convert units for things like padding-bottom percentages to pixels since the hero is typically 100% in width.

Oh! And remember to reset your values before and after the breakpoints in the calc() function. Otherwise you’ll end up with either very big or very small values for the target properties.

What say you?

This is probably just one way we can handle the situation and it was primarily driven by my interest in the calc() function. So, that begs the question: how have you handled scaling hero component height? Have you put calc() to use for it? Do you prefer wrangling breakpoints at various widths? Is there something else you use? Light up the comments!

The post Fun Tip: Use calc() to Change the Height of a Hero Component appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]