Handling Events – React

handling-events-with-react

What is Event?

Events are the activities to which javaScript can respond. For example:

  • Clicking an element
  • Submitting a form
  • Scrolling page
  • Hovering an element

Handling Events:

The handling of React events is very similar to the handling of DOM events. There are some syntactic differences:

  1. React events are named using camelCase, rather than lowercase.
  2. With JSX you pass a function as the event handler, rather than a string.

In HTML

Event In React:

Event with Function Component:

Class Component:

Note:- onClick is a camelCase Naming Convention in React. In HTML we have to use clickMe() but In React we have to use only clickMe or this.clickMe. Not need to use () with clickMe in React.

You can’t return false to prevent default behavior to React. You must call preventDefault explicitly.

Prevent default behavior in HTML:

In the above example, you can return false to prevent default behavior with onclick event.

Prevent default behavior In React:

In the above example, you can not return false to prevent the default behavior. For this, you need to pass “e” (synthetic event) as an argument in the function and write e.preventDefault() before any statement in React.

When using React you should generally not need to call addEventListener to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered.

Event Handler with Class Component

In the above example, When you will use class component then you need to bind “this” event handler in the constructor to access state value in the “clickme” event.

if you will not bind “this” object then it will show an error in clickme event that state is not defined.

If you don’t want to bind this event handler in the constructor then, you can use an arrow function in the callback.

For Example:

In the above example, you can see an arrow function in-class component. An Arrow function automatically bind this.

If you will use Above arrow function instead of the normal function, then you don’t need to bind this like this.clickme=this.clickme.bind(this) in construction.

State in React Component

Props in ReactJS

What is JSX in React?

Related posts