skip to Main Content

I have an array that I’ve confirmed has content, and the keys are correct.

I’m trying to iterate through that array and put an image via the item.url key into an Antd Card element. Below is the code I have. It compiles fine, but there is no output.

What needs to change to iterate over the array AND display the results of the Card elements thats being created?

        return(<div>{this.imageDetails.forEach((item) => {
                    <Card hoverable cover={<img src={item.url}/>}>
                        <Meta title="Unoptimized Image" description="Need to optimize"/>
                    </Card>})}
              </div>)
    }

2

Answers


  1. Use map function to return component like so

    return(
      <div>
          {this.imageDetails.map(item => (
              <Card hoverable cover={<img src={item.url}/>}>
                  <Meta title="Unoptimized Image" description="Need to optimize"/>
              </Card>)}
      </div>
    );
    
    Login or Signup to reply.
  2. The difference between forEach and map is that forEach is used to iterate through an array and returns undefined, while map can also iterate through an array, but it returns a new array (of JSX elements in this case). With map, you can create dynamic length lists in React. Additionally, curly braces are used to denote code blocks, while parentheses (in React) are used to create JSX elements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search