Reputation: 15
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
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.
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
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
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