Solution: Cloudinary
Using Cloudinary API resolves most of our problems. Making a long story short, Cloudinary manages your media assets in the cloud. It covers all the hard work listed in our problematic points from 1 to 4 above. You can see Cloudinary.
We just need to create a component that handles points 5 to 8.
React-Cloudinary-lazy-image
When Cloudinary is doing their work, we can focus on ours. Let’s handle lazy loading by using the React-Cloudinary-lazy-image.
- It allows us to start the image download only when the element is within a user’s screen.
- Of course, we don’t want our page to jump, so it thinks about rendering a placeholder.
- What’s more, it would be cool not to have an empty space waiting for the image. We can either set some background colour or load a very small version of the original image.
- At last, we can create breakpoints in order to have different sizes on different screens adding source set to image tags.
Example 1
Have a look at this code:
1// Speed Up Technique Code Example 1
2import React from 'react';
3import Img from 'react-cloudinary-lazy-image';
4
5export const LazyImage = () => (
6 <Img
7 cloudName="CloudName"
8 imageName="black-hole"
9 fixed={{
10 width: 800,
11 height: 600,
12 }}
13 alt="black_hole"
14 />
15);
And here is the result:
This is an example of a fixed version of the component. It’s made for cases where the image won’t change its size on smaller screens. To handle it properly, height and width should be set in a fixed property. The cloudName and imageName params are passed directly to Cloudinary. First is just a cloud name, and second is public id in Cloudinary assets. To have all set, it’s good practice to pass alt property as well.
Example 2
On the other hand, it’s common to have a full-width picture on the website. A fixed-size asset won’t solve the problem, so there is a fluid version. The fluid parameter takes an object with one or two keys, maxWidth is required and defines the max size of the picture, which will be than scale down, both width and height. However, often images stay the same of similar height despite screen width. To have it constant you can also pass height key.
All values in both image types should be numbers in pixels.
This is the code example:
1// Speed Up Technique Code Example 2
2<Img
3 cloudName={‘CloudName’}
4 imageName={'black-hole'}
5 fluid={{
6 maxWidth: 800,
7 height: 300
8 }}
9 alt={'black_hole'}
10/>