How can I render images in a loop in React?

I am trying to create a card with a title, description and an image.

My file structure looks like:

src
 -components
 -images
 -section
   -Featured.js

In a config.js file I have:

module.exports = {

  featuredSection: [
    {
      name: 'beer-image-1',
      title: 'Mango Cart',
      description:
        'A light Wheat Ale bursting with lots of 
         fresh mango flavor and aroma, finishing 
         crisp and refreshing.',
    },
  ],
};

In my Featured.js component file I have tried:

const Featured = () => {
...

// Get array of all names in config file
const featuredNames = featuredSection.map((beer) => beer.name); // --> ['beer-image-1']

// Return an image for each name in `featuredNames` array
const images = featuredNames.map((image) => {
  return (
    <img
      key={image}
      src={require(`../images/${image}.jpg`)}
      alt='Beer picture'
    />
  );
});


  // Return title, desc., and image
  const card = featuredSection.map((image, i) => {
    return (
      <div key={i}>
        <h1>{image.title}</h1>
        <p>{image.description}</p>
        {images}
      </div>
    );
  });

  return <>{card && card}</>;
}

This returns the title, and description but the image is not loading and only shows the alt text.

I’ve been trying to make use of these examples but it always results in the alt text showing up.

Answer

Can you move your images folder to public folder? If you can the below code should work

<img
  key={image}
  src={`./images/${image}.jpg`}
  alt='Beer picture'
/>

If you cannot move the images folder try below. Use the default property of require. Its should have the image src.

const images = featuredNames.map((image) => {

  const img = require(`../images/${image}.jpg`).default;

  return (
    <img
      key={image}
      src={img}
      alt='Beer picture'
    />
  );
});