Cloudinary Blog

Cloudinary Image Gallery with Stencil Custom Components

Cloudinary Image Gallery with Stencil Custom Components

When you need to build small custom web components that can be used across all frameworks - Angular, React, Vue vanilla JS and others - Stencil is an ideal tool. Stencil enables you to create platform-independent components that can be exported as a true web component and used anywhere.

Check out our StencilJS Posts:

This article shows how to build an image gallery with Cloudinary-stored images using Stencil. Cloudinary is an end-to-end image and video management solution. The Cloudinary Image API is very easy to use and exposes image manipulation techniques via HTTP URLs. If you have never used Stencil, you can get started with this article.

Setup a Media Library and a Stencil Project

Let's start with uploading some images to the Cloudinary server and setting up a Stencil project.

Create a Cloudinary Account

We will upload images using the Cloudinary dashboard. In real projects, however, you should have a server that uses the Cloudinary SDK to upload these images.

  1. Create a Cloudinary account by signing up for the free plan, offering 300,000 images.
    Cloudinary Sign Up
  2. On your server dashboard/console, click on Media Library in the navigation bar.
  3. Use the image upload widget on the Media Library page to add images to your server.
    Cloudinary Media Library

Create a Stencil Project

The first thing we need to do with Stencil is to set up a boilerplate for a Stencil project. Fortunately, the Ionic team provides a starter template to simplify this setup process. All you need to do is clone this starter template, install the template and start your new project:

# Clone
git clone https://github.com/ionic-team/stencil-starter.git cl-gallery

# Enter project
cd cl-gallery

# Remove original Github history
git remote rm origin

# Install dependencies
npm install

Create a Gallery Data Source

A typical gallery app or widget requires a data source. Most real situations would probably require fetching these data from a server or an API endpoint. There is no need for that in this app. We are going to create a mock data that looks like what a server would send to us.

Create db.ts in your src directory with the following content:

Full code available HERE

Just an export of an array of gallery images. Each gallery item is represented as an object with an image ID, collector/author and description about the image. The image ID (imageId) is the same ID you get when you upload an image to Cloudinary server. We can use the these IDs to fetch the images from Cloudinary.

Deliver and Transform Images with Cloudinary SDK

The browser will not understand an image ID. We need to use the Cloudinary SDK to convert image IDs to URLs. This process is known as “delivery.”

We also need to define a width and quality attribute for the image. This process is done with the SDK and referred to as “transformation.”

Before we dive into these, let's first create a container component to serve as our app shell and interact with Cloudinary. Create a folder site in the components directory with the following contents:

  • app-site.scss
  • app-site.tsx

Then update theapp-site.tsx file with the following content:

import { Component } from '@stencil/core';
import cloudinary from 'cloudinary-core';
import data from '../../db';

@Component({
  tag: 'app-site',
  styleUrl: 'app-site.scss'
})
export class Site {

  cloudinary = null;
  galleryImages = [];

  componentWillLoad() {
    this.cloudinary = cloudinary.Cloudinary.new({
      cloud_name: ''
    })
    this.galleryImages = data.map(this.transform.bind(this));
  }

  transform(image) {
    const imageUrl =
      this.cloudinary.url(image.imageId, { width: 300, crop: "fit", quality: 'auto', secure: true });
    return Object.assign(image, { imageUrl });
  }

  render() {
    return (
      <div class="wrapper">
        <nav>
          <div>CL Gallery</div>
        </nav>
        <div class="gallery-images">
          {this.galleryImages.map(image => 
            <cl-gallery-item image={image}></cl-gallery-item>
          )}
        </div>
      </div>
    );
  }
}
  • Stencil looks very much like React because it uses JSX and has a resemblance in syntax. A component is defined as a class, but it is decorated with the Component decorator that we imported from the Stencil core above. The tag in the decorator is what is used to mount this component in a containing template, while the styleUrl is the SCSS file that defines the component's styles.
  • The class has two properties, cloudinary and galleryImages. cloudinary is going to keep a reference to the configured Cloudinary instance. This configuration happens when the component is about to be mounted in componentWillLoad. galleryImages keeps references to the array of images from our data source.
  • componentWillLoad is executed before component loads, so we are setting up Cloudinary and our data store before the component is rendered. To configure Cloudinary, pass in the cloud name from your Cloudinary server.
  • The data store is transformed before being passed to galleryImages. It's transformed with a transform method, which generates a URL and transforms the image using the object passed as second argument.
  • Finally, we use JSX to render a child component, cl-gallery-item that receives each item from the galleryImages via props.

Rendering Images with Child Component

Create another component folder, cl-gallery-item with the following files:

  • cl-gallery-item.scss
  • cl-gallery-item.tsx

The following logic should be in your TSX file:

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


@Component({
  tag: 'cl-gallery-item',
  styleUrl: 'cl-gallery-item.scss'
})
export class ClGalleryItem {

  @Prop() image: any;

  render() {
    return (
      <div class="cl-gallery-item">
        <img src={this.image.imageUrl} alt=""/>
        <h3>{this.image.collector}</h3>
        <p>{this.image.description}</p>
      </div>
    );
  }
}

The only change here is that we decorate a property with Prop. This property is called image and maps to the property that was passed to this component from the parent component, app-site.tsx. The property holds a gallery item, which we can then display using JSX.

Update App's Entry Point

Originally, this project has one component, which is the default component. The component is named my-name. Open index.html and you will see it's right there, so even if you keep running the app with all these changes, the visuals will never update.

Update the index.html and replace my-name component with app-site and we are good to go:

<html dir="ltr" lang="en">
<head>
 ...
</head>
<body>

  <app-site></app-site>

</body>
</html>

Run the following command to see the app running at port 3333:

npm start

You should see a simple grid like the one shown below:

Stencil final example

Feel free to check out the code on GitHub.

Conclusion

Stencil is quite promising and it stands out because of its ability to export components that are compatible with any other JavaScript environment. It enables you to write light components for widgets, like a Cloudinary Gallery; export the components; and import them in your Angular, React or Vue project. Cloudinary offers more than what we just discussed, including file upload, image manipulation, image optimization, and more. You can learn about all these features or get started for free.

Recent Blog Posts

 New Image File Format: FUIF:Lossy, Lossless, and Free

I've been working to create a new image format, which I'm calling FUIF, or Free Universal Image Format. That’s a rather pretentious name, I know. But I couldn’t call it the Free Lossy Image Format (FLIF) because that acronym is not available any more (see below) and FUIF can do lossless, too, so it wouldn’t be accurate either.

Read more
Optimizing Video Streaming and Delivery: Q&A with Doug Sillars

Doug Sillars, a digital nomad and a freelance mobile-performance expert, answers questions about video streaming and delivery, website optimization, and more.

Doug Sillars, a freelance mobile-performance expert and developer advocate, is a Google Developer Expert and the author of O’Reilly’s High Performance Android Apps. Given his extensive travels across the globe—from the UK to Siberia—with his wife, kids, and 11-year-old dog, Max, he has been referred to as a “digital nomad.” So far in 2018, Doug has spoken at more than 75 meetups and conferences!

Read more
Building a Music Discovery Service

In May 2018, Cloudinary sponsored Capitol Music Group’s first hackathon held by its new Capitol360 Innovation Center, which aims at connecting musicians and software technologists to facilitate and stimulate the creation of music. See this interview for details. As a starter project for the hackathon, we built a sample app called Music Discovery Service.

Read more
Once a Hackathon Participant, Now a Judge

Over the past several years, I've had a chance to participate in hackathons, as part of teams that developed a social payment app and helped users decide meals to cook. But it wasn't until last month that I got to experience a hackathon from the other side, as a judge.

Read more
10 Website Videos Mistakes and How to Solve Them

It should come as no surprise that video use on the internet is exploding. You can see the dramatic growth of video on the average site in this SpeedCurve blog post.

With the growth in video comes greater bandwidth use, which is not only costly for your IT budget, but for your visitors as well. Beyond the expense, there is the user experience to consider. The heavier the page, the longer it will take to load, and the greater likelihood visitors will abandon your site. Page load speed is also an important factor in SEO ranking, so clearly video is something we need to take seriously and get right. Video is challenging, presenting terms still unfamiliar to developers - like codecs, bitrate and adaptive bitrate streaming. As a result, mistakes are being made in video implementation.

Read more
Android Data Saver: Optimizing Mobile Data Usage with Cloudinary

Over the life of a mobile device, the cost of a cellular data plan often exceeds that of the device itself. To optimize data usage and purge useless data on their mobile devices, users can enable Data Saver from Android 7.0 (API level 24). To do so, users toggle Data Saver in quick settings under the Notification shade or under Settings > Data usage. With Data Saver enabled, apps that aren't whitelisted cannot use cellular data in the background. They are also directed to consume less data while active.

Read more