How to create a link in React component with onClick handler?
29,943
Solution 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
href="javascript:void(0)"
is better than href="#"
.
href="#"
will cause the url changed.
Solution 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
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.
Author by
Artegon
Updated on July 09, 2022Comments
-
Artegon almost 2 years
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>
.-
Phil Hauser almost 7 yearsDepends where you want the link to go. If it's for internal app navigation, then the routing library will likely have a
<Link>
component that will do this for you, otherwise you will have to just use css to style it like a link. But again I would suggest making an independent component to do this.
-
-
Lars Blumberg about 7 years
href="javascript:void(0)"
will evoke a warning if you use linting:warning Script URL is a form of eval no-script-url