ReactJS – Events

Events in React.js involves handling user interactions like clicks, form submissions, key presses, etc. React normalizes events to ensure consistency across different browsers and provides a way to handle these events in a declarative way using event handlers.

Event Handling in React

  1. Synthetic Events: React uses synthetic events, which are wrappers around the browser’s native events. This ensures consistent behavior across different browsers.
  2. Event Handlers: Event handlers are functions that are triggered in response to user interactions.

Adding Event Handlers

Event handlers in React are passed directly to JSX elements as props. The naming convention for event handlers in React is camelCase, e.g., onClick, onChange, onSubmit, etc.

Example: Button Click Event

Let’s create a simple example to demonstrate event handling in React.

Step 1: Create a New React Application

First, create a new React application if you don’t have one already.

npx create-react-app my-app
cd my-app
npm start

Step 2: Create an Event Handling Component

Create a new file ButtonClick.js and add the following code:

import React, { useState } from 'react';

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

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

export default ButtonClick;

Step 3: Use the Event Handling Component

Modify the App.js file to include the ButtonClick component:

import React from 'react';
import './App.css';
import ButtonClick from './ButtonClick';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>React Event Handling Example</h1>
        <ButtonClick />
      </header>
    </div>
  );
}

export default App;

Explanation:

  1. State Management:
    • The ButtonClick component uses the useState hook to create a state variable count and a function setCount to update the state.
  2. Event Handler:
    • The handleClick function increments the count state by 1 each time the button is clicked.
  3. JSX and Event Binding:
    • The button element has an onClick attribute that is set to the handleClick function. This means that whenever the button is clicked, the handleClick function is called.

More Event Handling Examples

Handling Form Submission

Create a new file FormSubmit.js and add the following code:

import React, { useState } from 'react';

function FormSubmit() {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  }

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`A value was submitted: ${value}`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={value} onChange={handleChange} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

export default FormSubmit;

Modify the App.js file to include the FormSubmit component:

import React from 'react';
import './App.css';
import ButtonClick from './ButtonClick';
import FormSubmit from './FormSubmit';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>React Event Handling Example</h1>
        <ButtonClick />
        <FormSubmit />
      </header>
    </div>
  );
}

export default App;

Explanation:

State Management:

The FormSubmit component uses the useState hook to create a state variable value and a function setValue to update the state.

Event Handlers:

The handleChange function updates the value state whenever the input value changes.

The handleSubmit function prevents the default form submission behavior and displays an alert with the submitted value.

JSX and Event Binding:

The input element has an onChange attribute that is set to the handleChange function.

The form element has an onSubmit attribute that is set to the handleSubmit function.

Summary

  • Synthetic Events: React normalizes events to ensure consistent behavior across different browsers.
  • Event Handlers: Functions that are triggered in response to user interactions.
  • Event Binding: Event handlers are passed directly to JSX elements as props.

These examples demonstrate how to handle events in React, including button clicks and form submissions. Understanding event handling is crucial for creating interactive and responsive web applications with React.


Tutorials Deck

TutorialsDeck is striving to provide the best learning material on technical and non-technical subjects.

Languages

Web Technologies

Database

Trending Technologies

© 2024. All rights reserved.

Contact Us @ tutorialsdeck06@gmail.com