React Events

  • React events are interactions or occurrences in a React application that trigger specific functions or actions.
  • They allow developers to respond to user input and create dynamic, interactive user interfaces.

Handling Events in React

  • React events are similar to standard DOM events but are camelCased, like onClick instead of onclick.
  • Event handlers are functions that are invoked in response to a specific event.

Example: Handling Click Events

In a functional component:

import React from 'react';

const ButtonClick = () => {
  const handleClick = () => {
    alert('Button Clicked!');
  };

  return (
    <button onClick={handleClick}>Click Me</button>
  );
};

In a class component:

import React, { Component } from 'react';

class ButtonClickClass extends Component {
  handleClick() {
    alert('Button Clicked!');
  }

  render() {
    return (
      <button onClick={this.handleClick}>Click Me</button>
    );
  }
}

Passing Parameters to Event Handlers

Use an arrow function or bind to pass parameters to event handlers.

import React from 'react';

const ParameterizedClick = () => {
  const handleClick = (message) => {
    alert(`Button Clicked! ${message}`);
  };

  return (
    <button onClick={() => handleClick('with parameters')}>Click Me</button>
  );
};

Form Handling

Forms in React use controlled components where the state manages the form's input values.

import React, { useState } from 'react';

const FormExample = () => {
  const [inputValue, setInputValue] = useState('');

  const handleChange = (e) => {
    setInputValue(e.target.value);
  };

  return (
    <form>
      <input type="text" value={inputValue} onChange={handleChange} />
    </form>
  );
};

Preventing Default Behavior

Use preventDefault() to stop the default behavior of an event, like form submission.

import React from 'react';

const FormPreventDefault = () => {
  const handleSubmit = (e) => {
    e.preventDefault();
    alert('Form Submitted!');
  };

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
};

 

Summary

Understanding React events is fundamental for creating interactive and responsive user interfaces. Whether handling simple click events or managing form submissions, React provides a consistent and powerful event system.