Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

href with onClick in ReactJS

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.

like image 559
TechTurtle Avatar asked Mar 22 '17 21:03

TechTurtle


People also ask

Can you add onClick to 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.

How do you open a link in another tab in React?

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.


1 Answers

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.

like image 149
Vincent D'amour Avatar answered Oct 13 '22 22:10

Vincent D'amour