Creating engaging user interfaces often requires a delicate balance between functionality and visual appeal. In this article, we'll explore how to build a dynamic image grid component using Svelte that not only manages state efficiently but also provides smooth, eye-catching transitions as images swap in and out.
Imagine a grid of images that periodically refreshes itself, with individual cards smoothly flipping to reveal new images.
This creates an engaging display perfect for showcasing team members, product catalogs, or any collection of images that's larger than what can be shown at once.
This is what I had to build this for an image grid widget showcasing a members list. The members images come from an API and grow over time.
I decided to build this with Svelte because, why not ?!
More seriously, I wanted something that will be compiled to just the necessary amount of code required and have a really small footprint on the website.
Based on that I had two options:
Furthermore, I find the svelte model to be simpler and more intuitive so given the choice, especially on a small project like this one, that's what I'll default to.
As you will see a little further, svelte makes dealing with a lot of small and intricate state changes really simple compared to other solutions (again, personal taste).
There are usually less ways to mess things up.
Our implementation consists of two main Svelte components:
The heart of our widget lies in its state management. We need to track several pieces of information:
let allImages: Image[]; // All available images let imagesToUse: Image[] = []; // Initial grid images let imagesInUse: Image[] = []; // Current grid state let remainingImages: Image[] = []; // Pool of unused images let imagesSwapMap = new Map<number, Image>(); // Tracks pending swaps
You might wonder why we maintain imagesInUse separately from imagesToUse. This separation serves several crucial purposes:
The image swapping process is a carefully orchestrated sequence that ensures smooth transitions while maintaining grid integrity. Let's break down the switchImages function step by step:
let allImages: Image[]; // All available images let imagesToUse: Image[] = []; // Initial grid images let imagesInUse: Image[] = []; // Current grid state let remainingImages: Image[] = []; // Pool of unused images let imagesSwapMap = new Map<number, Image>(); // Tracks pending swaps
First, we need to determine which images from our remaining pool will be used for swapping:
const switchImages = () => { let newImagesSwapMap = new Map<number, Image>() let remainingImagesToUse let newRemainingImages: Image[]
This code handles two scenarios:
Next, we randomly select positions in the grid where we'll swap images:
if (remainingImages.length <= NUMBER_OF_IMAGES_TO_SWITCH) { // If we have fewer remaining images than needed, use all of them remainingImagesToUse = remainingImages.slice(0); newRemainingImages = []; } else { // Take the last N images from the remaining pool remainingImagesToUse = remainingImages.slice(-NUMBER_OF_IMAGES_TO_SWITCH); // Keep the rest for future swaps newRemainingImages = remainingImages.slice(0, -NUMBER_OF_IMAGES_TO_SWITCH); }
This creates an array of random indexes within our grid size. For example, if NUMBER_OF_IMAGES_TO_SWITCH is 1 and NUMBER_OF_IMAGES_TO_USE is 16, we might get [7], indicating we'll swap the image at position 7 in the grid.
Before performing any swap, we check if the new image is already displayed:
indexesToSwap = Array(NUMBER_OF_IMAGES_TO_SWITCH) .fill(null) .map(() => Math.floor(Math.random() * NUMBER_OF_IMAGES_TO_USE));
This function prevents the same image from appearing multiple times in our grid.
Now comes the core swapping logic:
const imageIsInUse = (image: Image) => { const inUse = imagesInUse.find((img: Image) => image.picture_url === img.picture_url); return inUse; };
Let's break down what happens in each swap:
After performing all swaps, we update our state:
for (let i = 0; i < indexesToSwap.length; i++) { let index = indexesToSwap[i]; let imageToSwap = imagesInUse[index]; // Current image in the grid let imageToSwapWith = remainingImagesToUse.pop(); // New image to display if (imageToSwapWith && !imageIsInUse(imageToSwapWith)) { // Record the swap in our map newImagesSwapMap.set(index, imageToSwapWith); // Update the swap map to trigger component updates imagesSwapMap = newImagesSwapMap; // Update the grid state imagesInUse[index] = imageToSwapWith; // Add the old image back to the pool newRemainingImages.unshift(imageToSwap); } else { return; // Skip if the image is already in use } }
The imagesSwapMap is the key to triggering animations. When it updates, the relevant MemberImageCard components react:
remainingImages = newRemainingImages; imagesInUse = imagesInUse;
This reactive statement in MemberImageCard:
The beauty of this system is that it maintains a smooth user experience while ensuring:
Each MemberImageCard component manages its own flip animation using CSS transforms and transitions. The magic happens through a combination of state tracking and CSS:
let allImages: Image[]; // All available images let imagesToUse: Image[] = []; // Initial grid images let imagesInUse: Image[] = []; // Current grid state let remainingImages: Image[] = []; // Pool of unused images let imagesSwapMap = new Map<number, Image>(); // Tracks pending swaps
const switchImages = () => { let newImagesSwapMap = new Map<number, Image>() let remainingImagesToUse let newRemainingImages: Image[]
When an image needs to swap, we:
To enhance the user experience, we implemented a progressive loading effect:
if (remainingImages.length <= NUMBER_OF_IMAGES_TO_SWITCH) { // If we have fewer remaining images than needed, use all of them remainingImagesToUse = remainingImages.slice(0); newRemainingImages = []; } else { // Take the last N images from the remaining pool remainingImagesToUse = remainingImages.slice(-NUMBER_OF_IMAGES_TO_SWITCH); // Keep the rest for future swaps newRemainingImages = remainingImages.slice(0, -NUMBER_OF_IMAGES_TO_SWITCH); }
Images start blurred and fade in smoothly once loaded, providing a polished look and feel.
The regular image swaps are scheduled using Svelte's onMount lifecycle function:
indexesToSwap = Array(NUMBER_OF_IMAGES_TO_SWITCH) .fill(null) .map(() => Math.floor(Math.random() * NUMBER_OF_IMAGES_TO_USE));
This implementation showcases the power of Svelte's reactive capabilities combined with modern CSS transforms to create a dynamic, engaging UI component.
The above is the detailed content of Building a dynamic image grid with Svelte: implementing flip card transitions. For more information, please follow other related articles on the PHP Chinese website!