Home > Enterprise >  What's the best way to show multiple static images in a React app?
What's the best way to show multiple static images in a React app?

Time:04-28

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

CodePudding user response:

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>
      )
   });

CodePudding user response:

{[img1, img2....].map((image, i) => (
  <Col key={i}>
    <img src={image} />
  </Col>
)}

this is an easy/correct way to do it

  • Related