Event handling in ReactJS

Tram Ho

In the lesson, I will guide you “How to use Event (event) in ReactJS”. It’s also not much different when you use events in ReactJS compared to using events in Javascript.

    1. In Javascript you will handle events in a function, while in React you will handle events in a Component method.

ReactJS Events

React is a Javascript-based library, which basically doesn’t have much difference in event handling between ReactJS and Javascript. With Javascript, when an event occurs, a function will be called to execute. But with React, when an event occurs, there will be a Component method called.

OK, let’s first see a simple example:

File onClick-example.jsx

File onClick-example.html


Arrow Function

With Javascript ES6 syntax you can create an arrow function , very short and easy to understand:

onClick , onChange , ..

onClick must call a Javascript function, it cannot call a Component method directly. So onClick should call an anonymous function, and inside this anonymous function you can call the Component method:

Arrow function with event parameter:

With Javascript ES6 you can also call Component ‘s method in the following way:

File onClick-example3.jsx


Thank you for reading! (bow)

Share the news now

Source : Viblo