How to redirect to external url onClick? in React
Asked Answered
S

4

9

I'm using react-router which means i'm storing routes in app.tsx file.

I have cards components that need to redirect to an external url onClick.

So my question is how to redirect onClick on card component using the external url example: www.test.com and give to that url two query strings a=xxx and b=xxx

Stivers answered 1/4, 2021 at 13:10 Comment(2)
Does this answer your question? React-Router External linkExtemporaneous
Thank you, but i need to use query strings in my external url so here i cant find that.Stivers
H
4

You can redirect to an external URL with dynamic query strings with template literals:

const onClick = () => {
  location.href = `www.test.com/?a=${queryA}&b=${queryB}`
}

where queryA and queryB are your dynamic injected query strings

Hebbe answered 1/4, 2021 at 13:30 Comment(0)
G
8

You can also use window.open()

The open() method of the Window interface loads a specified resource into a new or existing browsing context (that is, a tab, a window, or an iframe) under a specified name.

Parameters:

url: a string indicating the URL or path of the resource to be loaded. If an empty string ("") is specified or this parameter is omitted, a blank page is opened into the targeted browsing context.

target (optional): a string, without whitespace, specifying the name of the browsing context the resource is being loaded into. If the name doesn't identify an existing context, a new context is created and given the specified name. The special target keywords, _self, _blank, _parent, and _top, can also be used.

Example

Once you click the card the external link will open on a new tab.

const url = 'https://www.test.com'

function Card(){
  return(
    <div 
      className='card-wrapper'
      onClick={() => window.open(url, '_blank')}  
    >
      <span>Some content here</span>
    </div>
  )
}
Grumpy answered 4/5, 2022 at 7:26 Comment(0)
H
4

You can redirect to an external URL with dynamic query strings with template literals:

const onClick = () => {
  location.href = `www.test.com/?a=${queryA}&b=${queryB}`
}

where queryA and queryB are your dynamic injected query strings

Hebbe answered 1/4, 2021 at 13:30 Comment(0)
P
3

Is that what you need?

const onClick = () => {
    location.href = 'http://<location>/?a=1';
}
Purdum answered 1/4, 2021 at 13:23 Comment(0)
S
3

location.href not works ?

Facing this erros

Unexpected use of 'location' no-restricted-globals

if you are using React ^18, need you add window before location

let url = 'https://www.external.url/'

<Button onClick={() => { window.location.href = url; } }>
   Click Here
</Button>
Sopher answered 11/8, 2022 at 11:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.