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

2
  • 1
    Use something like: const imageBoxes = images.map((image, index) => <JSX />). You can then render <div>{imageBoxes}</div> into your main render, or do the .map directly in there. Commented Oct 29, 2019 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)'}}" Commented Oct 29, 2019 at 11:58

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

3 Comments

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
I have updated the example. You can use template literal to define the variable. Here is the link to read more: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
I have also added an example with the same use case. Hope this will help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.