Loading
Current section: Implementation 12 exercises
lesson

DynamicallyAdd Images to the Cards

Using IDs from Unsplash images, we are going to add real images to our component.

Let's start by creating an array containing the image IDs:


const imageIds = [
"1500462918059-b1a0cb512f1d",
"1531581147762-5961e6e2e6b1",
"1626204327506-0d3ee11d7752",
"1549068106-b024baf5062d",
];

Ne

Loading lesson

Transcript

00:00 The next thing we'll do is add an image to each of these cards. And I've prepared four images that I will paste here. These are IDs from Unsplash images. Instead of having a self-closing <li> item here, we're going to have our image tag inside. And so here for the source, I will paste an Unsplash URL.

00:20 And so that works. We have our image from Unsplash. And I want to use these four image IDs. And essentially that image ID, you can see it highlighted in the URL, goes after this photo dash here. So I'll turn this into a template tag.

00:35 And here, instead of the hard-coded photo ID, I will use image IDs. And then we want to basically use the loop index to, on the first iteration of our array, get the first ID, and then the second, etc. So I need to grab here the index.

00:53 And since we're not really going to use the item itself, I can use an underscore as a convention for something we're not using. And voila, we now have four beautiful images from Unsplash that we can work with. So we want the images to cover the entire card and sort of work as a background because

01:12 they're going to use the whole space even when we expand. And then we have this text coming over it. So let's do that now. Since we're going to have text over it, I want to make this image absolutely positioned. So on the Li item, I will add a position of relative. And then on the image, absolute.

01:31 The height will be full and the width will be full as well. Let's make sure it always covers the entire parent with inset zero. And right now we have two problems. It's distorted and it's also going over the rounded corners of the parent.

01:47 So on the parent, let's add overflow hidden so that the rounded corners are respected. And to fix the skewing of the image, I will add the class of object fit cover, which will basically crop the image to maintain its aspect ratio. And here we go. This is looking pretty nice.

02:07 Notice that we're not going for a pixel perfect replica here. We're really trying to get the interesting effect of this hover state and the cards getting fluidly wider and narrower. So it doesn't really matter if the border radius or the aspect ratio or anything is not the same.