skip to Main Content

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


  1. Your problem lies in the fact that src={img} instead of src={imgs}

    You can try it:

    {
       imgs.map((img, index)=>(<img src ={img} key={index}/>));
    }
    
    Login or Signup to reply.
  2. In your code first you declare images state as integer so using
    imgs.map() gives imgs.map() not a function so declare it like

     const [imgs, setImgs] = useState([]);
    

    and in your loop statment

     const imgArr = imgs.map((img)=> {
             return <img src ={imgs}/>
          }); 
    

    in above loop each image stored in img variable but you give value to source imgs array its gives error change to

    {imgs.map((img)=> ( <img src ={img}/>)); }
    

    final code

     import React from "react";
    import { useState, useEffect} from 'react';
    
    export default function Gallery() {
       const [imgs, setImgs] = useState([]);
      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>
       
          {imgs.map((img)=> ( <img src ={imgs}/>));
      
          </div>
    )};
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search