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:
http://localhost:3000/google.com/maps/dir/?api=1&origin=50.4984,%20-2.6119074&destination=50.927044,-1.299964&travelmode=driving
I've tried setting target="_blank" when calling the compnent.
Any help would be greatly appreciated!
Thanks, Max
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With