'How to create a link in React component with onClick handler?
What is proper / standard way how to create link with onClick callback function without URL
?
<a href="#" onClick={this.handleClick}>click me!</a>
or without href
, but then a link is not visually clickable:
<a onClick={this.handleClick}>click me!</a>
All tutorials, I have read, work with another element than <a>
- clickable <span>
, <div>
etc. but I would like to use <a>
.
Solution 1:[1]
You may set cursor: pointer;
for a link to achieve behavior of real url link :)
<a onClick={this.handleClick} style={{cursor: 'pointer'}}>click me!</a>
Solution 2:[2]
href="javascript:void(0)"
is better than href="#"
.
href="#"
will cause the url changed.
Solution 3:[3]
For anchor tag in REACT, if we want to use onClick without URL change, then can use the following
<a
style={{ cursor:"pointer" }}
href={null}
onClick={() =>
this.toggleModal("Rental Objects With Current Rent")
}
>
Click Me
</a>
OR
<a
style={{ cursor:"pointer" }}
href={void (0)}
onClick={() =>
this.toggleModal("Rental Objects With Current Rent")
}
>
Click Me
</a>
Note: Instead of cursor:pointer we can also use in CSS file
a:not([href]):not([tabindex]){
cursor: pointer;
color: #0086ce;
}
Solution 4:[4]
import { withRouter } from 'react-router-dom';
import Button from '../../components/CustomButtons/Button';
onRegister = () => {
this.props.history.push('/signupAsTeacher');
};
<Button onClick={this.onRegister}> Contact Us </Button>
export default withRouter(functionName);
You must first import withRouter. Then you should give the page path to the button click event. The last one is the export withRouter.
Solution 5:[5]
Eslint says to use a button:
[eslint] Anchor used as a button. Anchors are primarily expected to navigate. Use the button element instead. [Error]
<button
type="button"
onClick={this.onBtnClick.bind(this, key)}
>
{link[key]}
</button>
Solution 6:[6]
This is one of the easiest way:
<a href="/" onClick={this.handleClick}></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 | 1ven |
Solution 2 | |
Solution 3 | |
Solution 4 | Önder ?ahin |
Solution 5 | bloke_zero |
Solution 6 | Blastfurnace |