Home > Back-end >  How can i render only first image from my array of objects?
How can i render only first image from my array of objects?

Time:03-03

I have an array of objects which contain products details. On the object, there is an images array of objects property where all the images with id are there. I am trying to render only the first image from that array of objects. I have tried to set 0 indexes to render only the first object but I got an error.

My database:

[
{
    _id: "asdasdds",
    title: "Title",
    reg_price: string
    images: [
        {
            id: "a1e73da66ddb9191984e3128b0df78af"
            src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
        },
 {
            id: "a1e73da66ddb9191984e3128b0df78af"
            src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
        },
    ]
},
{
    _id: "asdasdds",
    title: "Title",
    reg_price: string
    images: [
        {
            id: "a1e73da66ddb9191984e3128b0df78af"
            src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
        },
 {
            id: "a1e73da66ddb9191984e3128b0df78af"
            src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
        },
{
            id: "a1e73da66ddb9191984e3128b0df78af"
            src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
        },
    ]
}
]

Here is my code: when I set 0 index product.images[0] I got map doesn't exist error.

{
        products.map(product => {
            return <tr>
                <td className="px-5 py-5 border-b border-gray-200 bg-white text-sm">
                    <div className="flex items-center">
                        <div className="flex-shrink-0 w-10 h-10">

                            {                  
                                product.images[0].map(({ src }) => <img className="w-full h-full rounded-full"
                                    src={src}
                                    alt="" />)
                            }
                        </div>

                    </div>

CodePudding user response:

You don't need to map at all. Just directly refer to the 0 indexed element's src property

{products.map(product => (
  <tr>
    <td className="px-5 py-5 border-b border-gray-200 bg-white text-sm">
      <div className="flex items-center">
        <div className="flex-shrink-0 w-10 h-10">
          <img
            alt=""
            className="w-full h-full rounded-full"
            src={product.images[0]?.src ?? "some-placeholder.png"}
          />
        </div>
      </div>
    </td>
  </tr>
)}
  • Related