Skip to main content

React: Implementing Keys In Lists

Series

This is part 2/3 in a series making a responsive masonry image grid in React, with images pulled from Unsplash using an API, queried from a text input in a small sample app.

Mapping The Array

Let us take our ImageList component where we are passing in our array of images that we have received from the Unsplash api and then mapping it to a new array and returning it to our app.

const ImageList = (props) => {
console.log(props.images);
const images = props.images.map((image) => {
return <img src={image.urls.small} />;
});

return <div>{images}</div>;
};

Adding Unique ID

So far on each item in our mapped array we are just returning the URL, now let us add the ID so that each item has a key.

const ImageList = (props) => {
console.log(props.images);
const images = props.images.map((image) => {
return <img key={image.id} src={image.urls.small} />;
});

return <div>{images}</div>;
};

export default ImageList;

It’s really that simple. The ID is a property that already exists on each item in the original array, we are now just adding it to each item in our new mapped array images.

Optional: Adding Alt Tags

We can also easily add an alt tag to each image like so.

const ImageList = (props) => {

const images = props.images.map((image) => {
return <img key={image.id} src={image.urls.small} alt={image.description} />;
});

return <div>{images}</div>;
};

Destructuring Properties

To clean up the function you can de-structure the properties if you wish like so.

const ImageList = (props) => {

const images = props.images.map(({id, urls, description}) => {
return <img key={id} src={urls.small} alt={description} />;
});

return <div>{images}</div>;
};

Personally I think this adds an unnecessary layer of abstraction so I would avoid this.

Comments

Recent Work

Free desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.

Learn More

BidBear

bidbear.io

Bidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.

Learn More