This post is about “ReactJS Handling Events”. Event handling is a common thing in most of the programming languages. Just some syntax changes. If you are familiar with any web languages, you can correlate things here. Some of the languages are case sensitive and some are not. But if you remember React is case sensitive, so be careful if you are just using notepad to type the code. Sometime a small Caps letter will need your attention for hours 🙂
Previous Post : Click Here
Example:
in HTML we use the code for event as:
<script>
Function dosomething(){
//some logic here
}
</script>
<button onclick=”dosomething()”>
Click for some action
</button>
But here we will do something like:
<button onClick={dosomething}>
Click for some action
</button>
Another difference is that you cannot return false to prevent default behavior in React. You must call preventDefault explicitly. For example, with plain HTML, to prevent the default link behavior of opening a new page, you can write:
<a href=”#” onclick=”console.log(‘The link was clicked.’); return false”>
Click me
</a>
In React we will write:
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log(‘The link was clicked.’);
}
return (
<a href=”#” onClick={handleClick}>
Click me
</a>
);
}
For this post, I will be using some previously written code. You can download from here if you already have the environment ready.
Quick look at the code:
If you see the code, we are using the “HandleClick” function as our event handler, in this case it is with the event onClick. If you write onclick it will not work, so be careful. You can use any other events as well such as onFocus, onBlur,onDoubleClick etc.
Conclusion
This was a quick intro to “ReactJS Handling Events”. Play around with the code if you are interested and share your comments with all our subscribers.
Keep reading and sharing …… bye till the next post.
Leave a Reply