Mapping Images in React js

Using the .map() method in React is a great way to render a list of elements, such as images, dynamically from an array. Here's a simple example of how to use .map() to render a set of images from an array of image URLs

import React from 'react';

const ImageGallery = () => {
  const images = [
    "https://via.placeholder.com/150",
    "https://via.placeholder.com/200",
    "https://via.placeholder.com/250",
    "https://via.placeholder.com/300",
  ];

  return (
    <div style={{ display: 'flex', gap: '10px' }}>
      {images.map((src, index) => (
        <img
          key={index}
          src={src}
          alt={`Image ${index + 1}`}
          style={{ width: '100px', height: '100px', objectFit: 'cover' }}
        />
      ))}
    </div>
  );
};

export default ImageGallery;

Explanation

  1. images array: An array of image URLs.
  2. .map(): Iterates over each src (image URL) in the array, creating an <img> element for each.
  3. key prop: Each <img> element has a unique key based on its index. This helps React optimize rendering.
  4. Styling: Inline styles adjust the display for better layout control (optional).

Usage

Include <ImageGallery /> in your component tree, and it will render the set of images side by side. Adjust the URLs or add more to render additional images.