image - How to create React component that can render Img or Video depending on API data it recieves -


i learning , practicing react.

i trying achieve react web app allows display , scroll through nasa's picture of day based on date choose. here's api: api.nasa.gov/

the project simple but. url api returns, leads img , youtube video. example:

https://apod.nasa.gov/apod/image/1708/perseidsturkey_tezel_960.jpg

or

https://www.youtube.com/embed/zy9jiikx62o?rel=0

i have managed display both cases using iframe. know not ideal imgs because cannot format css , looks bad scroll bars, sizing etc..but won't display video..

this react component looks (using bootstrap)

detail.js

import react, { component } 'react';  export default class detail extends component {   render() {     return (       <div classname="video-detail col-md-12">         <div classname="embed-responsive embed-responsive-16by9">             <iframe classname="embed-responsive-item" src={this.props.url}>             </iframe>             </div>         </div>     );   } } 

i images display responsively, centered , original aspect ratio still have videos display are.

i have tried putting additional <img> underneath <iframe> renders image twice. there way render <img> or <iframe> conditionally?

i wondering strategy should try next? ideas?

thanks!

you should use conditional rendering

const isimage = this.props.url.split().pop() === 'jpg'; return (    {      isimage ? <img src={this.props.url} />      : <iframe classname="embed-responsive-item" src={this.props.url}>         </iframe>     } ) 

or

const isimage = this.props.url.split().pop() === 'jpg'; return (    {      isimage && <img src={this.props.url} />    }    {       !isimage && <iframe classname="embed-responsive-item" src={this.props.url}>         </iframe>     } ) 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -