4

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.

Olawale Oladiran
  • 561
  • 2
  • 11
  • 19
  • 2
    When your website gets built, the path to the images is probably different. Usually the JS is compiled into a single bundle at the root of the build folder, so the path from that bundle to the image is different than the path from the JS source file to the image. Check that paths and file locations of your *compiled* JS – Jayce444 May 31 '20 at 01:28
  • How do I check that? – Olawale Oladiran May 31 '20 at 01:48
  • @OlawaleOladiran depends how you're building your app. But there should be a folder where the built stuff gets put when it's compiled. – Jayce444 May 31 '20 at 03:08

2 Answers2

10

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.

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
2

I think you are missing require.

Like:

<img src={require(item.image)} />
ilovecoffee
  • 66
  • 1
  • 3