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>``
CodePudding user response:
Your handleLink1
should be like this.
const handleLink1 = () => {
window.open(data.url);
}
<button onClick={handleLink1} className="btn-primary"> {data.buttonName}</button>
CodePudding user response:
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 :)
CodePudding user response:
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>
);
}
CodePudding user response:
let home = "https://explorer.solana.com/tx/" url;
window.open(home);
This is the perfect source code.