1

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.

agw2021
  • 266
  • 2
  • 22

2 Answers2

3

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'
    />
  );
});
kiranvj
  • 32,342
  • 7
  • 71
  • 76
  • Using the `.default` worked! What exactly did that change? – agw2021 Aug 25 '21 at 04:26
  • @agw2021 require returns an object, if you look at the img src in console you will see something like `` The actual src will be in `default` property. Please see [this](https://github.com/facebook/create-react-app/issues/9721) also – kiranvj Aug 25 '21 at 04:37
1

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