Reputation: 604
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>
URLText
is just a styled component(div).
If item.url
is google.com
, it opens a new tab with url localhost:3000/example/google.com
,
instead of opening just google.com
.
Upvotes: 0
Views: 1237
Reputation: 2721
Try this way.
<URLText onClick={() => window.open('//'+item.url, '_blank')}>Click</URLText>
Sample fiddle - https://jsfiddle.net/pecu0szq/12/
Upvotes: 1
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
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