'skip undefined objects from a map array in react

I have an array called carousel.cards. He has 14 objects. I want to render images (called carouselHome) inside this objects. Only 2 objects have an image. I want to filter the 12 objets left who are undefined.

What am I doing wrong please ?

        <div className="embla__container-home">
          {carousel.cards.map((image) => {
            if (image.fields.carouselHome !== undefined)
              <img
                src="image.fields.carouselHome.fields.file.url"
                alt="Image d'acceuil"
              />;
          })}
        </div>


Solution 1:[1]

You're missing a return so it doesn't return a node to render.

And if it's empty just return a document fragment or null.

        <div className="embla__container-home">
          {carousel.cards.map((image) => {
            if (image.fields.carouselHome !== undefined)
              return <img
                src="image.fields.carouselHome.fields.file.url"
                alt="Image d'acceuil"
              />;

            return <></> // or null;
          })}
        </div>

EDIT: brainfart; a cleaner solution would be to use filter:

carousel.cards.filter((image) => image.fields.carouselHome))...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hittingonme