in

React: Implementing Keys In Lists 🔑

This is part 2/3 in a series making a responsive image grid in React.

Part 1: Working With API’s, Mapping Arrays & Looping Images

Part 3: Responsive Image Grid

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>;
};

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.

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>;
};

De-structure 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.

React Logo

React: Working With API’s, Mapping Arrays & Looping Images

React Logo

React: Responsive Image Grid