7

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

Gass
  • 7,536
  • 3
  • 37
  • 41
Kate
  • 288
  • 2
  • 4
  • 17
  • 1
    Does this answer your question? [React-Router External link](https://stackoverflow.com/questions/42914666/react-router-external-link) – callmemath Apr 01 '21 at 13:11
  • Thank you, but i need to use query strings in my external url so here i cant find that. – Kate Apr 01 '21 at 13:19

4 Answers4

3

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

Al Duncanson
  • 743
  • 9
  • 16
3

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>
  )
}
Gass
  • 7,536
  • 3
  • 37
  • 41
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>
GMKHussain
  • 3,342
  • 1
  • 21
  • 19
2

Is that what you need?

const onClick = () => {
    location.href = 'http://<location>/?a=1';
}
Yoskutik
  • 1,859
  • 2
  • 17
  • 43