Saturday, May 25, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  108] [ 5]  / answers: 1 / hits: 146805  / 7 Years ago, wed, march 22, 2017, 12:00:00

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.


More From » reactjs

 Answers
4

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.


[#58433] Tuesday, March 21, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elliem

Total Points: 415
Total Questions: 117
Total Answers: 94

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
;