1

I've just started to learn React. I've zero experience so go easy.

I have 4 images that I want to display horizontally across my app.

I know I can just do

import Image1 from './Image1.png` 
import Image2 from './Image2.png`
... 

And then within my app.js I can add something like

<Col> 
  <img src ...> 
</Col>
<Col> 
  <img src ...> 
</Col>

I've looked at the documentation and can't really find the correct way. What's the best way to avoid creating <Col> </Col> for every image?

Hope this makes sense?

Thanks

isherwood
  • 52,576
  • 15
  • 105
  • 143
JacksWastedLife
  • 215
  • 1
  • 8
  • If you're wondering how to loop over a list, that's [well documented](https://reactjs.org/docs/lists-and-keys.html). – isherwood Apr 27 '22 at 18:18
  • Does this answer your question? [Import multiple images on React](https://stackoverflow.com/questions/64922587/import-multiple-images-on-react)_ – isherwood Apr 27 '22 at 18:20
  • Or this? [How to make an image class which renders multiple images in react](https://stackoverflow.com/questions/66363008/how-to-make-an-image-class-which-renders-multiple-images-in-react) – isherwood Apr 27 '22 at 18:21

2 Answers2

1

you can create new component to contain col and img called imageWrapper

function ImageWrapper({src}) {
  return <Col> 
     <img src={src}> 
    </Col>
}

then use it

<ImageWrapper src...>
<ImageWrapper src...>

also you can use array for images then use map like this

import Image1 from './Image1.png' 
import Image2 from './Image2.png'
const arrayImage=[ Image1 , Image1 ]

return arrayImage.map((image)=>{
   return (
       <Col> 
        <img src={image}> 
       </Col>
      )
   });
Yoel
  • 6,035
  • 6
  • 23
  • 51
0
{[img1, img2....].map((image, i) => (
  <Col key={i}>
    <img src={image} />
  </Col>
)}

this is an easy/correct way to do it

c0dm1tu
  • 551
  • 3
  • 8