0

Hi all I have following code: my code

I am receiving some response from backend.

I am trying to get all images from imagesData and show in ImageComponent component.

I am using map function in my main component in this way:

{!!res &&
    res.map((data) => 
    {
     return <ImageComponent key={data.publicId} {...data} />;
    })}

and here is my ImageComponent component:

const ImageComponent = ({ img }) => {
  return (
   <div>
     <img src={img} alt="pic" />
   </div>
  );
};

But something went wrong please help me to resolve this problem.

1
  • A question to your code: does the variable "rest" contain a json object? Commented Apr 1, 2021 at 8:06

2 Answers 2

1

You're applying the map method on res, which is an object not an array. Map method is made for Arrays. All you have to do is access the image array present in you Object and then, apply the map.

Read about map here

  return (
    <div className="App">
      {!!res &&
        res.imagesData.map((data) => {
          return <ImageComponent key={data.publicId} {...data} />;
        })}
    </div>
  );

In your ImageComponent, you have to pass url in your destructured props as it is the url property that contains the actual url of your image


const ImageComponent = ({ url }) => {
  return (
    <div>
      <img src={url} alt="pic" />
    </div>
  );
};
Sign up to request clarification or add additional context in comments.

Comments

0

res is not an array.

From what I see I suppose you wanted to do this

{!!res &&
    res.imagesData.map((data) => 
    {
     return <ImageComponent key={data.publicId} {...data} />;
    })}

2 Comments

yes res in not an array, but my all images are in imagesData array, by the way I try as you write but still not working :/ codesandbox.io/s/hungry-franklin-bowhf
don't know why but you have res.ImagesData not res.imagesData codesandbox.io/s/pensive-https-tqrlh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.