Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 437
max Avatar asked Jun 01 '19 22:06

max


2 Answers

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.

like image 80
user2950720 Avatar answered Oct 04 '22 22:10

user2950720


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.

like image 39
max Avatar answered Oct 05 '22 00:10

max