How to Display All Imagefrom Array in Reactjs

How I can display all imagefrom Array in reactJS?

What you did was inserting the array of gifs from the api inside the state array, like this { gifs: [[gifsarr]]} response.data.data is already an array of objects so just assign them to this.state.gifs

An empty array will always return true if you check for if (this.state.gifs) {} you will have to check if the length is > 0

class Content extends React.Component {
constructor() {
super();
this.state = {
gifs: []
};
}

componentDidMount() {
axios
.get(
"https://api.giphy.com/v1/gifs/trending?api_key=nNwaquW24K8gLDmrxGTmawppQoTkXxLQ&tag=&rating=G"
)
.then(response => {
this.setState({ gifs: response.data.data }); // This line is different
})
.catch(function(error) {
console.log(error);
});
}

render() {
if (!this.state.gifs.length) return null;

return (
<div className="container">
{/* gif is an object and not an array you dont need to access it by index */}
{this.state.gifs.map(gif => (
<div className="card mt-5" style={{ width: 224 + "px" }} key={gif.id}>
<img
className="card-img-top"
src={gif.images.preview_gif.url}
alt="test"
/>
<div className="card-body">
<h4 className="card-title">{gif.title}</h4>
</div>
</div>
))}
</div>
);
}
}

sandbox

I only returning 1 card an an image from the array of objects using React js

What you need to store in the images constant is just the result of calling map() on your displayImages array. So assuming you have:

const displayImages = [
{
filePath: "imageFile",
locationName: "name1"
},
{
filePath: "imageFile",
locationName: "name2"
}
];

this is how your component should look like:

const images = displayImages.map((displayimage, key) => (
<div key={key}>
<div className="card bg-light mb-3">
<div className="card-header">
<center>{displayimage.locationName}</center>
</div>
<div className="card-body">
<div className="imgDiv">
<img src={displayimage.filePath} />
</div>
</div>
</div>
</div>
));
return <div>{images}</div>;

Working stackblitz

I Want To Display The ImagesUrl's In The Array according To The Number of images the Array has, using Reactjs

you can loop over the images and show them:

using map:

...
images.map((image) => {
return <div>
<img src={image} alt="title" />
</div>
})
...

Display image from .map array (React)

Using src in the img tag to render image

 <img className="icon" key={item.weather[0].icon} src={`https://openweathermap.org/img/w/${item.weather[0].icon}.png`} />

And put the key in div instead in the children.



Related Topics



Leave a reply



Submit