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
  • 58,414
  • 16
  • 114
  • 157
JacksWastedLife
  • 254
  • 2
  • 15
  • 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
  • 7,555
  • 6
  • 27
  • 59
0
{[img1, img2....].map((image, i) => (
  <Col key={i}>
    <img src={image} />
  </Col>
)}

this is an easy/correct way to do it

codmitu
  • 636
  • 7
  • 9