'In reactJS, how to invoke link click via button press?
I have a button. When the users presses it, I want the outcome ot be the same as if the user had pressed a specific link.
Put another way, I want to represent a link as a button.
I can see from this that it is possible using Jquery: How to call a href by onclick event of a button?
What is the "correct" way to do this in ReactJS?
Solution 1:[1]
Like this:
<button
type="button"
onClick={(e) => {
e.preventDefault();
window.location.href='http://google.com';
}}
> Click here</button>
Solution 2:[2]
Use React-Router Link,instead of Anchor tag.
import React, { Component } from 'react';
import {Link} from 'react-router-dom'
// reactClass --
return (
<div>
<Link to='https://react.semantic-ui.com/'>
<button type="button" className="btn btn-info">Button</button>
</Link>
</div>
);
// end--
Solution 3:[3]
You don't even need jQuery nor React to do that. It's as simple as this:
var ex = document.getElementById('ex');
ex.onclick = function(){
console.log('clicked');
}
var bt = document.getElementById('bt');
bt.onclick = function(){
ex.click();
}
<button id="bt">Click</button>
<a id="ex">Triggerable link</a>
Of course, in React you can store the ref of the components, bind to the event and then trigger the event like this:
onClick(){
this.ex.click();
}
render(){
return (
<div>
<button id="bt" onClick={this.onClick.bind(this)} ref={(ref)=>{this.bt = ref}}>Click</button>
<a id="ex" onClick={()=>console.log("clicked")} ref={(ref)=>{this.ex = ref}}>Triggerable link</a>
</div>
)
}
Edit: If you just want a button that behaves like a link, you can use this, or any of the solutions listed in this question:
onClick(){
window.location.href="http://url.com";
}
render(){
return (
<button id="bt" onClick={this.onClick}>Click</button>
)
}
Solution 4:[4]
2021 Update :
<div
style={{
width: 15,
height: 15,
background: "blue",
cursor: "pointer",
}}
onClick={() => {
window.open("http://google.com", "_blank");
}}
/>
Solution 5:[5]
This worked for me :)
<a target="_blank" href="http://google.com"> <button id="bt" >Click</button> </a>
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 | Suz |
| Solution 2 | Saurabh |
| Solution 3 | |
| Solution 4 | Ghassane AB |
| Solution 5 | Murugan Venkat |
