Sometimes, we want to invoke link click via button press in React.
In this article, we’ll look at how to invoke link click via button press in React.
How to invoke link click via button press in React?
To invoke link click via button press in React, we can set the window.location.href
property to the string of the URL that we want to go to.
For instance, we write:
import React from "react";
export default function App() {
return (
<div>
<button
type="button"
onClick={(e) => {
e.preventDefault();
window.location.href = "https://example.com";
}}
>
Click here
</button>
</div>
);
}
to set the onClick
prop of the button to a function that goes to https://example.com when we click the button.
We do this by setting window.location.href
to "https://example.com"
.
Conclusion
To invoke link click via button press in React, we can set the window.location.href
property to the string of the URL that we want to go to.