Hello Sunil
event-target-javascript-feature-image

How to Use event.target in JavaScript and React: A Beginner’s Guide

In web development, events are actions or occurrences that happen in the browser, such as clicks, form submissions, or key presses. To handle these events, JavaScript provides an event object, which contains valuable information about the event, including the event.target property.

This blog post will explore what event.target is in JavaScript, how it works, and how to use it effectively in React applications.

The event.target property is part of the event object in JavaScript that refers to the specific element that triggered the event.

This means that when an event occurs, event.target points to the exact element where the event originated, allowing developers to identify which element was interacted with.

Consider the following simple example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Target Example</title>
</head>
<body>
    <button id="myButton">Click Me</button>
    <script>
        document.getElementById("myButton").addEventListener("click", function(event) {
            console.log(event.target); // Logs the button element
            console.log(event.target.id); // Logs "myButton"
            console.log(event.target.textContent); // Logs "Click Me"
        });
    </script>
</body>
</html>

In this example, when the button is clicked, the event.target property refers to the button element itself. We can access its properties, such as id and textContent, to get more information about the clicked element.

In React, event handling is slightly different, but the concept of event.target remains the same. React automatically passes the event object to event handler functions, making it easy to access event.target.

Let’s create a simple form that utilizes event.target to manage input changes dynamically.

import React, { useState } from 'react';

const MyForm = () => {
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: ''
  });

  const handleChange = (event) => {
    const { name, value } = event.target; // Destructure name and value from event.target
    setFormData({
      ...formData, // Spread the existing form data
      [name]: value // Update the specific field
    });
  };

  const handleSubmit = (event) => {
    event.preventDefault(); // Prevent the default form submission
    console.log('Form submitted:', formData); // Log the form data
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="username">Username:</label>
        <input
          type="text"
          id="username"
          name="username" // Set the name attribute
          value={formData.username} // Controlled input
          onChange={handleChange} // Handle input changes
        />
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          name="email" // Set the name attribute
          value={formData.email} // Controlled input
          onChange={handleChange} // Handle input changes
        />
      </div>
      <div>
        <label htmlFor="password">Password:</label>
        <input
          type="password"
          id="password"
          name="password" // Set the name attribute
          value={formData.password} // Controlled input
          onChange={handleChange} // Handle input changes
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;

Explanation

State Management:

  • We use the useState hook to manage form data. The state formData holds the values of the inputs.

Handling Input Changes:

  • The handleChange function is called every time an input changes.
  • By destructuring name and value from event.target, we can determine which input field triggered the change and its new value.
  • We then update the corresponding field in formData using computed property names.

Form Submission:

  • The handleSubmit function prevents the default form submission and logs the current state of formData.

Controlled Inputs:

  • Each input is a controlled component, with its value tied to the formData state. This ensures that the state always reflects the current value of the inputs.

Using event.target is particularly useful in scenarios such as:

  • Dynamic elements: When you have multiple buttons or inputs that trigger the same event, event.target helps you identify which one was interacted with.
  • Forms: Handling multiple input fields efficiently without needing separate handlers for each field.

In JavaScript, the notation [name]: value is used in the context of object properties, specifically when creating or updating objects.

This syntax is known as computed property names, and it allows you to use the value of a variable as a key in an object.

Here’s a detailed explanation of how it works, especially in the context of React and form handling.

When defining an object, you can use square brackets to create a property name dynamically. This means the key for that property can be determined at runtime based on the value of a variable.

Example in Object Creation:

Suppose you have a variable name that holds the string "username". You can create an object with a dynamic key like this:

const name = 'username';
const value = 'JohnDoe';
const user = {
  [name]: value // This will create an object like { username: 'JohnDoe' }
};
console.log(user); // Output: { username: 'JohnDoe' }

Use Case in Form Handling:

  • In the context of form handling in React, using [name]: value is particularly useful when you have multiple input fields in a form that all share the same change handler. Each input has a name attribute that corresponds to a key in the form data state.
  • For example, when handling a change event, you can update the state like this:
const handleChange = (event) => {
  const { name, value } = event.target; // Destructure name and value from event.target
  setFormData({
    ...formData, // Spread the existing state
    [name]: value // Update the specific field using computed property name
  });
};
  • In the code above, when an input field changes, event.target provides the name of the field (e.g., “username”) and its new value (e.g., “JohnDoe”).
  • The setFormData function is called with a new object that includes all the existing fields in formData (using the spread operator …formData), along with the updated field. The [name]: value syntax dynamically assigns the new value to the corresponding field in the state.

Using [name]: value is a powerful way to dynamically update object properties based on variable values.

In the context of React forms, it enables efficient state management for multiple input fields, making your code cleaner and easier to maintain.

This pattern allows you to handle changes for various inputs with a single change handler, significantly simplifying your component logic.

Understanding event.target is essential for effective event handling in JavaScript and React.

It allows developers to identify the specific element that triggered an event, making it easier to manage user interactions.

By leveraging event.target in your React applications, you can create dynamic and responsive forms and interfaces. Experiment with these examples and integrate event.target into your projects to enhance user experience!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.