I have a coding challenge and i'm trying to fetch Imgur post from Imgur API and i'm trying to render images videos or gif. When i receive the data i get an image array which has information about the image which can be of "type" 'image/png or jpeg' gif or video. I'm trying to render them conditionally in case type is video i want to render a video element or image element because when i render only images i get empty photos
return (
<div className={styles.ImgurPost}>
<div className={styles.imageContainer}>
{image.images && image.images[0].type.startsWith("video")}
<video className={styles.video} src={image.images[0].link}></video>
{/* <img className={styles.image} src={image.images[0].link}></img> */}
</div>
<div className={styles.info}>
<p className={styles.description}>{image.title}</p>
</div>
</div>
);
This is the api return and it includes a "type"
account_id: 94569445
account_url: "DumpsterKoala"
ad_config: {safeFlags: Array(4), highRiskFlags: Array(0), unsafeFlags: Array(0), wallUnsafeFlags: Array(0), showsAds: true, …}
ad_type: 0
ad_url: ""
comment_count: 74
cover: "UIkJ0L6"
cover_height: 1323
cover_width: 1757
datetime: 1659932020
description: null
downs: 20
favorite: false
favorite_count: 33
id: "CS5NoBO"
images: Array(1)
0: {id: 'UIkJ0L6', title: null, description: null, datetime: 1659932007, type: 'image/jpeg', …}
length: 1
[[Prototype]]: Array(0)
images_count: 1
in_gallery: true
in_most_viral: true
include_album_ads: false
is_ad: false
is_album: true
layout: "blog"
link: "https://imgur.com/a/CS5NoBO"
nsfw: false
points: 423
privacy: "hidden"
score: 441
section: ""
tags: (2) [{…}, {…}]
title: "It do be like that"
topic: null
topic_id: null
ups: 443
views: 36223
vote: null
CodePudding user response:
Conditionally render using ternary operator
return (
<div className={styles.ImgurPost}>
<div className={styles.imageContainer}>
{image?.images?.[0]?.type && image.images[0].type.startsWith("video") ?
<video className={styles.video} src={image.images[0].link}></video> :
<img className={styles.image} src={image?.images?.[0]?.link}></img> }
</div>
<div className={styles.info}>
<p className={styles.description}>{image.title}</p>
</div>
</div>
);
CodePudding user response:
You can use the <object />
tag it will take care of the format for you