kd12345
kd12345

Reputation: 793

React Native conditional render

I currently have an IMAGES array that is supposed to display images if the index exists. With the current implementation, I have the images are being displayed if an index with an image exists and for index without images, a black screen gets displayed.

How do I change my code so that if an image doesn't exist it does not get added to the array?

Here is my code:

const IMAGES = [
  post.images[1]
    ? {
        url: post.images[1].url,
      }
    : [],
  post.images[2]
    ? {
        url: post.images[2].url,
      }
    : [],
  post.images[3]
    ? {
        url: post.images[3].url,
      }
    : [],
  post.images[4]
    ? {
        url: post.images[4].url,
      }
    : [],
  post.images[5]
    ? {
        url: post.images[5].url,
      }
    : [],
  post.images[6]
    ? {
        url: post.images[6].url,
      }
    : [],
  post.images[7]
    ? {
        url: post.images[7].url,
      }
    : [],
];

Upvotes: 0

Views: 90

Answers (4)

BHARAT BHUSHAN
BHARAT BHUSHAN

Reputation: 21

let IMAGES = [];
post?.images &&
  post.images.length > 0 &&
  post.images.map((eachImage, index) => {
    if ("url" in eachImage) {
      IMAGES.push(eachImage.url);
    }
  });

Upvotes: 2

Arfizur Rahman
Arfizur Rahman

Reputation: 394

This should do what you want:

const IMAGES = [];
post.images && post.images.map(image => {
    if(image && image.url) {
        IMAGES.push({url: image.url})
    }
})

Upvotes: 1

MUHAMMAD ILYAS
MUHAMMAD ILYAS

Reputation: 1450

Solution

const posts = {
    images: [
      {
        url: "https//1",
      },
      {
        url: "https//2",
      },
      {},
      {
        url: "https//3",
      },
      null,
      {
        url: "https//4",
      },
    ],
  };
  
const images = posts.images.map((item) => (item && item.url ? {url:item.url} : []));
console.log(images)  

Upvotes: 0

teddcp
teddcp

Reputation: 1624

You can use filter.

> post={}
 {}

> post.images ? post.images.filter( ele => ele.url) : null
 null

> post={ images:[ {}, {"url":"abc"}, {}, {"url": "cde"} ]}
 {images: Array(4)}

> post.images ? post.images.filter( ele => ele.url) : null
  (2) [{…}, {…}]


Upvotes: 0

Related Questions