'Open external link with function in React
I'm trying to create a button in React which opens an external link to a google maps url.
I have a function which asks the user for their geolocation, which once provided, inputs the location into the url link which gets directions from their geolocation to a set destination.
However, I'm struggling to get the button to firstly run the function and open the URL in a new tab. This is currently how I'm calling the button component.
<Button variant="primary" onClick={this.onHandleClick}>Get Google Maps Directions</Button>
And this is the function which forms and opens the link.
onHandleClick = () => {
var location = this.state.currentLocation;
location.then(function(location){
var link = `google.com/maps/dir/?api=1&origin=${location}&destination=50.927044,-1.299964&travelmode=driving`
//window.location.href = link;
window.location.assign(link);
})
}
Currently the external link forms correctly, but is appended to the existing localhost domain in the url so does not open currently (or in a new tab).
url result of the above functions:
I've tried setting target="_blank" when calling the compnent.
Any help would be greatly appreciated!
Thanks, Max
Solution 1:[1]
window.open(link, "_blank");
This will cause the link to open in a new tab.
Note: If you do not include "http://" or "https://" before the link, the default behavior is to append the link onto the current domain, so if you're opening an external link, be sure to include the http/s.
Solution 2:[2]
Answering in case it helps any people of the future...
As suggested by @user2950720, window.open method correctly oepns the link a new tab.
To stop the link from appending to localhost/, ensure to inlcude 'https://' at the start of the link.
Solution 3:[3]
Use
window.open(link, "_blank");
it will open a new window tab but if its keep on adding your site base url at the start just use // at the start of the linnk like
window.open(`\\${link}`, "_blank");
it will open new window and will not add base url of site
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jake T. |
| Solution 2 | max |
| Solution 3 | Bilal Khursheed |
