简体   繁体   中英

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.

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'
    />
  );
});

I think in the img JSX, the src attribute does not need to add require(). It simply would check for your directory structure based on your relative path.

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

Also, I think it can be map the featuredSection directly to get the image path. I admit that it would be convenient if your item's name is same as your image's name. it would like:

const card = featuredSection.map((item, i) => {
  return (
    <div key={i}>
      <h1>{item.title}</h1>
      <p>{item.description}</p>
      <img
        src={`../images/${item.name}.jpg`}
        alt='Beer picture'
      />
    </div>
  );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM