'Navigate to an external website on button Click
In my app users click on button and navigate to external website. This external website is picked dynamically based on a form they fill.
Here, on clicking the button is not working.
What I am doing wrong here?
const handleLink1 =()=>{
<Link
to={{
pathname: `${data.url}`
}}
target="_blank"
>
{' '}
</Link>
}
<button onClick={handleLink1} className="btn-primary"> {data.buttonName}</button>``
Solution 1:[1]
I didn't really understand your code, but I don't think returning <Link> from click handler function is the correct solution. <Link> from react-router will only provide you ways to navigate around routes of your app.
To navigate to external url, you can either make use of <a> tag or window.location.href or window.open() .I believe you meant to do
const handleLink1 = () => {
window.open(data.url, '_blank');
}
<button onClick={handleLink1} className="btn-primary"> {data.buttonName}</button>
or instead of button directly use
<a
class='btn-primary'
href=`${data.url}`
target='_blank'
rel="noopener"
aria-label='Github'
>
{data.buttonName}
</a>
correct me if I'm mistaken :)
Solution 2:[2]
Could you provide the code for handleLink1?
Anyways, if handleLink1 is anything like handleLink2, your mistake is creating a Link component in the event handler. It'll never be rendered. What you have to do instead, is wrap your button component in the Link component, like so:
<Link
to="somewhere"
>
<button className="some-class">Click me to go somewhere!</button> //No need for the onClick event handler.
</Link>
Edit
Maybe the below will help clarify:
import { useState } from "react";
import { Link } from "react-router-dom";
const IllNeverRender = () => {
return <p>Nope</p>;
};
const IllRender = () => {
return <p>Yep</p>;
};
export default function LinkButton() {
const [Component, setComponent] = useState();
const renderOnClickWrong = (event) => {
<IllNeverRender />; // This component isn't returned from the handler, nor would it render if it was returned.
};
const renderOnClickRight = (event) => {
setComponent(<IllRender />);
};
return (
// Only components returned from a functional component, or a React Component's render method, gets rendered.
<div>
<Link to={{ pathname: "/somewhere" }}>
<button>Go somewhere!</button>
</Link>
<button onClick={renderOnClickWrong}>Go nowhere.</button>
<button onClick={renderOnClickRight}>Render something.</button>
{Component}
</div>
);
}
Solution 3:[3]
let home = "https://explorer.solana.com/tx/" + url;
window.open(home);
This is the perfect source code.
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 | Sanjay |
| Solution 2 | |
| Solution 3 | Arthur Chen |
