Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

React.js - Event Handling

Event Handling in React.js

Event handling is a crucial aspect of building interactive user interfaces in React.js. You can attach event handlers to React components to respond to user actions like button clicks, form submissions, and keyboard input. Here's an overview of how event handling works in React:

1. Event Handling in JSX:

  • In JSX, you can attach event handlers to HTML elements using camelCase event names like onClick, onSubmit, onChange, etc.
  • Event handlers are assigned functions that will be executed when the event occurs.
  • Event handlers are typically defined as methods in class components or as arrow functions in functional components.

2. Handling Events in Functional Components:

import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  const handleIncrement = () => {
    setCount(count + 1);
  };

  return (
    

Count: {count}

); }    

 

 

3. Handling Events in Class Components:

import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  handleIncrement = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      

Count: {this.state.count}

); } }      

 

 

4. Event Object:

  • Event handlers receive an event object as their first parameter, which contains information about the event, such as the target element and event type.
  • You can access event properties like event.target.value for input elements.

5. Preventing Default Behavior:

  • In React, you typically call event.preventDefault() to prevent the default behavior of an event, like preventing a form submission or a link click.

6. Passing Arguments to Event Handlers:

  • To pass additional data to an event handler, you can define an anonymous arrow function inside the JSX.

       

 

 

7. Best Practices:

  • It's a good practice to use arrow functions for event handlers in functional components to ensure they have access to the component's this context.
  • Use event.preventDefault() when necessary to control default behaviors.
  • Avoid calling setState directly in event handlers. Instead, use the functional form of setState when the new state depends on the previous state.