The response from an api request is an array of image URLs and I’d like to display the images, but there are 100 images, and I’m trying to display them without coding each line. I tried to use map but am getting errors. I tried a for loop also got errors.
import React from "react";
import { useState, useEffect} from 'react';
export default function Gallery() {
const [imgs, setImgs] = useState(0);
const url = "http://shibe.online/api/shibes?count=100"
const getImgs = async () => {
try {
const response = await fetch(url)
const data = await response.json()
setImgs(data)
} catch (e) {
console.error(e)
}
}
useEffect(() => {
getImgs()
}, [])
return (
<div>
<h1>Gallery</h1>
<img src={imgs[0]} alt="shiba"/>
<img src={imgs[1]} alt="shiba"/>
{
const imgArr = imgs.map((img)=> {
return <img src ={imgs}/>
});
}
2
Answers
Your problem lies in the fact that
src={img}
instead ofsrc={imgs}
You can try it:
In your code first you declare images state as integer so using
imgs.map() gives imgs.map() not a function so declare it like
and in your loop statment
in above loop each image stored in img variable but you give value to source imgs array its gives error change to
final code