Olawale Oladiran
Olawale Oladiran

Reputation: 631

How to map images in reactjs

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.

Upvotes: 4

Views: 21212

Answers (3)

amnjore
amnjore

Reputation: 1

/* Use require in the array */

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

Upvotes: 0

Ajeet Shah
Ajeet Shah

Reputation: 19823

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.

Upvotes: 11

ilovecoffee
ilovecoffee

Reputation: 64

I think you are missing require.

Like:

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

Upvotes: 1

Related Questions