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>
.
To set an onClick listener on a link in React:Set the onClick prop on the link. The function you pass to the prop will get called every time the link is clicked.
There is an important difference between using onClick in React and onClick in HTML. To avoid the default behavior in HTML, we simply return false, but in ReactJS, the preventDefault method needs to be called explicitly. The onClick is an event handler for the target element within our React application.
To add the link in the menu, use the <NavLink /> component by react-router-dom . The NavLink component provides a declarative way to navigate around the application. It is similar to the Link component, except it can apply an active style to the link if it is active.
This is a type of JavaScript link - the onclick attribute defines a JavaScript action when the 'onclick' event for the link is triggered (i.e. when a user clicks the link) - and there is a URL present itself in the onclick attribute.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With