skarki
skarki

Reputation: 107

How to Add If…Else Statements in JSX without having 2 if statement?

I have two if statements written in ReactJS.

if (videoUrl !== undefined && videoUrl !== null && videoUrl.indexOf('youtube') !== -1) 
{
   videoUrl = videoUrl.replace("watch?v=", "embed/")
}
if (videoUrl !== undefined && videoUrl !== null && videoUrl.indexOf('vimeo') !== -1) 
{
   videoUrl = videoUrl.replace("https://vimeo.com/", "https://player.vimeo.com/video/")
}

I don't know how to make these if else statement, so it can check between youtube or Vimeo. Right now I can only use one if statement. If I leave both if statements on the place, one first if works.

Upvotes: 2

Views: 73

Answers (3)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22895

You don't need that many if, simply check for string

let videoUrl = 'https://vimeo.com/';
if (typeof videoUrl === 'string') {

  if(videoUrl.indexOf('youtube') !== -1) {
     videoUrl = videoUrl.replace("watch?v=", "embed/");
   }
   if (videoUrl.indexOf('vimeo') !== -1) {
     videoUrl = videoUrl.replace("https://vimeo.com/", "https://player.vimeo.com/video/");
   }
}

console.log(videoUrl);

// Another option is to use regex
videoUrl = 'https://vimeo.com/';
if (/youtube/.test(videoUrl)) {
   videoUrl = videoUrl.replace("watch?v=", "embed/");
}
if (/vimeo/.test(videoUrl)) {
  videoUrl = videoUrl.replace("https://vimeo.com/", "https://player.vimeo.com/video/");
}
console.log(videoUrl);

Upvotes: 2

immertreu
immertreu

Reputation: 41

I would write this as follows:

if (typeof videoUrl !== 'undefined' && videoUrl) {
  if (videoUrl.indexOf('youtube') !== -1) {
    //first case here
  } else if (videoUrl.indexOf('vimeo') !== -1){
    //second case here
  }
}

Upvotes: 0

Ken Y-N
Ken Y-N

Reputation: 15018

Just simply this:

if (videoUrl !== undefined && videoUrl !== null)
{
    if (videoUrl.indexOf('youtube') !== -1) {
        videoUrl = videoUrl.replace("watch?v=", "embed/")
    }
    else if (videoUrl.indexOf('vimeo') !== -1) {
        videoUrl = videoUrl.replace("https://vimeo.com/", "https://player.vimeo.com/video/")
    }
}

That removes the duplicate checks, and is easier to read. You cannot easily do it with a single if, unless you get into playing games with the ?: operator.

In fact, let's play games!

videoUrl = (videoUrl !== undefined && videoUrl !== null) ?
              (videoUrl.indexOf('youtube') !== -1) ? 
                  videoUrl.replace("watch?v=", "embed/") :
                  (videoUrl.indexOf('vimeo') !== -1) ?
                      videoUrl.replace("https://vimeo.com/", "https://player.vimeo.com/video/") :
                  null :
               null;

Or something like that - now that is unreadable!

Upvotes: 1

Related Questions