0

I have a javascript array of image sources. Now I need to implement each of the image source in individual box background. I am trying to put the array element into React JSX style element like below (demo code)

    const box = []

    for(const [index, image] of images.entries()) {
        box.push(
           <Box key={index} style={{background: 'url(image)'}}>
              Some code goes here.......
           </Box>
    )}

    return(<div>{box}</div>)

Hope I can make you understand my problem. Please help, any alternative way is always welcome. thank you in advance

johannchopin
  • 13,720
  • 10
  • 55
  • 101
Neel Debnath
  • 195
  • 11
  • 1
    Use something like: `const imageBoxes = images.map((image, index) => )`. You can then render `
    {imageBoxes}
    ` into your main render, or do the `.map` directly in there.
    – Jamie Dixon Oct 29 '19 at 11:54
  • @JamieDixon Thanks for the response but my question was how to integrate javascript variable into React JSX style element. Like in the "style={{background: 'url(image)'}}" – Neel Debnath Oct 29 '19 at 11:58

1 Answers1

1

For loop won't work directly in render function. you can use map instead

images.map((image, index) => (
  <Box key={index} style={{background: `url(${image})`}}>
       Some code goes here.......
  </Box>
))

Check this example: https://codesandbox.io/s/broken-frost-4iz90

You can check this as well: Loop inside React JSX

Hope this helps!

Yash Joshi
  • 2,586
  • 1
  • 9
  • 18
  • Thanks for the response but my question was how to integrate javascript variable into React JSX style element. Like in the "style={{background: 'url(image)'}}". Let me edit the code, it is creating confusion – Neel Debnath Oct 29 '19 at 12:00
  • 1
    I have updated the example. You can use template literal to define the variable. Here is the link to read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals – Yash Joshi Oct 29 '19 at 12:03
  • 1
    I have also added an example with the same use case. Hope this will help. – Yash Joshi Oct 29 '19 at 12:08