How to map images in reactjs

All we need is an easy explanation of the problem, so here it is.

So in a Reactjs class component, I have an array in my state like this:

myArray: [
   { number: 1, title: 'Users', image: '../../../assets/images/website/homepage/users.png' },
   { number: 2, title: 'Clients', image: '../../../assets/images/website/homepage/clients.png' },
   { number: 3, title: 'Admin', image: '../../../assets/images/website/homepage/admins.png' },
]

and I mapped the array this way:

{this.state.myArray.map((item, index) => (
   <Box key={index} className="col-sm-12">
      <img src={ item.image } className="img-fluid" alt={item.title} />
      <Typography variant="h4">{item.number}</Typography>
   </Box>
))}

Now, everything works fine, except the image that doesn’t display, I really don’t understand where I’m getting it wrong.

Note that, if I copy one of the image links directly inside the src using require method, it works. Kindly help.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can require dynamically with proper expression:

Change image to (remove ../../../assets/images/website/homepage/ and .png):

const myArray = [
  {
    number: 1,
    title: 'Users',
    image: 'users',
  },
  {
    number: 2,
    title: 'Clients',
    image: 'clients',
  },
  {
    number: 3,
    title: 'Admin',
    image: 'admins',
  },
]

And to render at UI (add directory path and the extension inside require):

{myArray.map((item, index) => (
  <Box key={index} className="col-sm-12">
    <img
      src={require('../../../assets/images/website/homepage/' +
        item.image +
        '.png')}
      className="img-fluid"
      alt={item.title}
    />
    <Typography variant="h4">{item.number}</Typography>
  </Box>
))}

Why it works?:

Webpack can understand this expression, by generating context about directory and extension, and can load all the matching modules.

Method 2

I think you are missing require.

Like:

<img src={require(item.image)} />

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply