'How to redirect to external url onClick? in React
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
Solution 1:[1]
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
Solution 2:[2]
Is that what you need?
const onClick = () => {
location.href = 'http://<location>/?a=1';
}
Solution 3:[3]
You can also use window.open()
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>
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | DrewCouturier |
Solution 2 | Yoskutik |
Solution 3 | Gass |