Roy Ra
Roy Ra

Reputation: 604

Opening new tab with url in react

I am trying to make a function to open a new tab with item.url. The problem is, the item.url property is given by client, not by me. So I cannot ensure if it starts with https:// or http://. For example, user can give google.com instead of https://google.com.

Below is my code. (This component is on /example)

<URLText onClick={() => window.open(item.url, '_blank')}>Click</URLText>

Upvotes: 0

Views: 1237

Answers (3)

Zam Abdul Vahid
Zam Abdul Vahid

Reputation: 2721

Try this way.

<URLText onClick={() => window.open('//'+item.url, '_blank')}>Click</URLText>

Sample fiddle - https://jsfiddle.net/pecu0szq/12/

Upvotes: 1

Sahil Raj Thapa
Sahil Raj Thapa

Reputation: 2483

You can use window.location.protocol to get the protocol of current url.

function handleURL(url) {
   if (url.includes("http://") || url.includes("https://")) {
      return window.open(url, '_blank')
   }

   window.open(`${location.protocol}//${url}`, '_blank')
}

<URLText onClick={() => handleURL(item.url)}>Click</URLText>

Upvotes: 0

Michael Rothkopf
Michael Rothkopf

Reputation: 128

Use this instead:

<URLText onClick={() => window.open((item.url.startsWith("http://") || item.url.startsWith("https://")) ? item.url : "http://" + item.url, '_blank')}>Click</URLText>

This uses the ternary operator to check if the passed URL contains https:// or http://, appends it to the beginning of the URL if it doesn't, and returns the appended or original value to the function parameter.

Upvotes: 0

Related Questions