Home > Software design >  How to display first image from a list of objects in react
How to display first image from a list of objects in react

Time:11-21

I am passing a prop called product which has a list of objects inside a variable images. I want to display first image with id number 1 on the frontend. Also if I want to iterate through the images what would be the best way. I have attached the object image as seen on postman as a photo. I am trying to display this line in the card <Card.Img src={product.images} />

{
    function Product({ product }) {
    return (
        
        <Card className="my-3 p-3 rounded">
            <Link to={`/product/${product._id}`}>
                <Card.Img src={product.images} />
            </Link>

            <Card.Body>
                <Link to={`/product/${product._id}`}>
                    <Card.Title as="div">
                        <strong>{product.name}</strong>
                    </Card.Title>
                </Link>

                <Card.Text as="div">
                    <div className="my-3">
                        <Rating value={product.rating} text={`${product.numReviews} reviews`} color={'#f8e825'} />
                    </div>
                </Card.Text>


                <Card.Text as="h3">
                    ${product.price}
                </Card.Text>
            </Card.Body>
        </Card>
    )
}

enter image description here

CodePudding user response:

try this, {product.images[0].image}

CodePudding user response:

<Card.Img src={product.images[0].image} />

would be the solution to show the first image.

and for the second, if i understood right, you should try to put a loop surrounding,

<Link to={`/product/${product._id}`}>
    <Card.Img src={product.images} />
</Link>

this, and render the data accordingly

  • Related