href with onClick in ReactJS
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.
the best way to fix this repeated function call on page load is to do
<a href="#" onClick={() => {this.handleClick}}>click me</a>