reactjsjsxreact-class-based-component

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.


Solution

  • 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.