As per Reactjs.org to handle event and prevent default use below code:
function ActionLink() { function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); } return ( <a href="#" onClick={handleClick}> Click me </a> ); }
However, this also requires to add binding in constructor like:
this.handleClick = this.handleClick.bind(this);
I was able to get desired behaviour by below code:
<span> <a href="#" onClick={()=>doSomething(arg1,agr2)}>Click here</a> </span>
Question: Which one is better option? It seems first one requires to use stateful component and second option can do the things irrespective of component being stateful or stateless.
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.
To open a link in a new tab in React, use the <a> element and set its target prop to _blank , e.g. <a href="https://google.com" target="_blank" rel="noopener noreferrer"></a> . The _blank value means that the resource is loaded into a new tab.
Both options produce almost the same result. Since ActionLink is a stateless component, handleClick
will be re-created and onClick
reallocated. If you want to get the best performance, you can use a class, something like this:
class ActionLink extends React.Component () { handleClick = (e) => { e.preventDefault(); console.log('The link was clicked.'); }; render() { return ( <a href="#" onClick={this.handleClick}> Click me </a> ); } }
In this example. the handleClick
is bound only once, and only the render method will be executed. You can also bind the handleClick
in the constructor if you prefer. But the differences are so small that I would suggest you use the one you prefer and you find it clearer.
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