Home > Enterprise >  React - use window.open to open a URL from a variable
React - use window.open to open a URL from a variable

Time:07-27

Sorry, if this is a stupid question, but I'm just trying to have a URL entered into a field and then a button that, when clicked, will take the value in that field and open a new tab to that URL. If I do this:

    onClick={event => {
                      event.preventDefault();
                      window.open('https://www.google.com/', '_blank');
    }}

Then it works just fine and opens a new tab with the specified url.

But if I set urlText = "https://www.google.com/" and do this:

onClick={event => {
                   event.preventDefault();
                   window.open({urlText},'_blank');
}}

Then it opens a new tab, but it goes to this instead:

http://theCurrentWebsiteDomain/[object Object]

I assume it's trying to add the urlText to the end of the current domain, like it's a page that I'm specifying instead of a whole new URL.

I added a console.log and it displays urlText just fine. If I click on it from the console, it goes right to the expected website.

What am I doing wrong?

CodePudding user response:

There is no need to add the curly braces around your urlText variable since it's within the event callback function. If it were to be used in the JSX then curly braces would be required (like <div>{urlText}</div> or <input type="text" value={urlText} />) - but since you're calling a function there is no need to wrap the variable name in curly braces.

The error is caused because by wrapping the urlText variable in curly braces, you are converting urlText to an object: { urlText: "foo" } and thus it appears as [object Object] in the URL bar since any object converted to a string will be literally '[object Object]'.

onClick={(event) => {
  event.preventDefault();
  window.open(urlText, "_blank");
}}

CodePudding user response:

Simply pass the string urlText directly into the function: window.open(urlText, '_blank') without curly brackets.

The curly brackets is syntax to create an object, this function takes in a string argument as its first parameter. So javascript parses your argument into a string [object Object], and due to there being no protocol in that it recognises it as a local path.

  • Related