RAGBOT
RAGBOT

Reputation: 15

How to make an image class which renders multiple images in react

Sorry for my bad English I am also fairly new to React (just started yesterday)

but I would like to know how we can render a variable number of images like if I specify the no of images with an array specifying the file names it should render all the images

like is a there


array = ["1.jpg", "2.jpg", "3.jpg"]
arrLen = array.length

render(
<MultipleImage 
    noOfImage = { arrLen}
    fileName = arrayOfFileNames
/>
);

Upvotes: 0

Views: 2157

Answers (3)

Saad Arshad
Saad Arshad

Reputation: 48

You can use the map() method to iterate the array of images. In this examle, I have passed the images[] array as a Prop to Image List component and in Image List component use the map method to itterate over all images.

Code Sandbox demo here

App.js Component

class App extends React.Component {

    state = {
        images: ["1.jpg", "2.jpg", "3.jpg"]
    }

  render() {
    return (
      <div className="ui container" style={{ marginTop: "1rem" }}>
        <ImageList images={this.state.images}/>
      </div>
    );
  }
}

Image List Component

const ImageList = (props) => {

    const images = props.images.map((image) => {
        return <img src={image} alt={image} />
    });
   return <div className="image-list">{images}</div>

}

Upvotes: 0

DecPK
DecPK

Reputation: 25408

You could use map to map over an array and render the image. codesandbox

In this example I've used picsum to simulate the source.

It would be better to create a new Image component so that you can use it again.

function Image({ fileName }) {
  return (
    <img  src={fileName}/>
  )
}

function App() {
  const array = ["1.jpg", "2.jpg", "3.jpg"]
  render(
    <>
      {
        array.map( image => {
          return (
            <Image fileName = { image }/>
          )
        })
      }
    </>
  );
}

Upvotes: 1

Abdl Imran
Abdl Imran

Reputation: 1

You can use the array map() method to loop the image source array and pass the single element of the array to the react component through props. here is an example. N.B: "you should learn about map(), and how to pass props in components"

    function Image(props) {
  return (
    <img  src={props.source}/>
  )
}

function App() {
  const images = ["1.jpg", "2.jpg", "3.jpg"]
  render(
    <>
      {
        images.map( img => 
          (
              <Image source = { img }/>
          )
      }
    </>
  );
}

Upvotes: 0

Related Questions