Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>.

like image 465
Artegon Avatar asked Apr 15 '16 08:04

Artegon


People also ask

How do I make an onClick link in React?

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.

Can we use onClick in link in ReactJS?

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.

How do I add a link to React component?

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.

Can a link have an onClick?

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.


1 Answers

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>
like image 100
1ven Avatar answered Oct 14 '22 07:10

1ven