DEV Community

Cover image for React Js Part 3 : Event Handling and Form Management
KyDev
KyDev

Posted on

React Js Part 3 : Event Handling and Form Management

Welcome back to our React series! In our last post, we discussed components, state, and props—fundamental concepts that lay the groundwork for building React applications. In this post, we will explore event handling and form management in React. Understanding these concepts will enable you to make your applications interactive and responsive to user input.

Understanding Event Handling in React

Event handling in React is similar to handling events in HTML and JavaScript, but with a few key differences. In React, events are named using camelCase and you pass a function as the event handler.

Basic Event Handling:

Let’s start with a simple example. Here’s how you can handle a button click event:

import React from 'react';

function ClickButton() {
    const handleClick = () => {
        alert("Button clicked!!!");
    };

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

export default ClickButton;
Enter fullscreen mode Exit fullscreen mode

In this example, when the button is clicked, the handleClick function is executed, displaying an alert.

Handling Events with Parameters
If you need to pass parameters to your event handler, you can use an arrow function:

function GreetingButton({ name }) {
    const handleClick = (name) => {
        alert(`Hello, ${name}!`);
    };

    return <button onClick={() => handleClick(name)}>Greet</button>;
}
Enter fullscreen mode Exit fullscreen mode

Here, the handleClick function takes a name parameter and displays a personalized greeting.

Preventing Default Behavior
In forms, you often want to prevent the default action (like a page reload) when submitting. You can do this using the event.preventDefault() method:

function Form() {
    const handleSubmit = (event) => {
        event.preventDefault();
        alert("Form submitted!");
    };

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

Form Handling in React

Forms are a common part of web applications, and managing form inputs in React requires a slightly different approach compared to traditional HTML forms.

Example of a Controlled Component:

import React, { useState } from 'react';

function ControlledForm() {
    const [inputValue, setInputValue] = useState('');

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

    const handleSubmit = (event) => {
        event.preventDefault();
        alert(`Submitted: ${inputValue}`);
    };

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

export default ControlledForm;
Enter fullscreen mode Exit fullscreen mode

In this example, the input value is controlled by the inputValue state variable. The handleChange function updates the state whenever the user types in the input field.

Multi-Input Forms
You can easily manage multiple inputs by storing their values in the component's state as an object.

Example of Multi-Input Form:

import React, { useState } from 'react';

function MultiInputForm() {
    const [formData, setFormData] = useState({ name: '', email: '' });

    const handleChange = (event) => {
        const { name, value } = event.target;
        setFormData({ ...formData, [name]: value });
    };

    const handleSubmit = (event) => {
        event.preventDefault();
        alert(`Name: ${formData.name}, Email: ${formData.email}`);
    };

    return (
        <form onSubmit={handleSubmit}>
            <input
                type="text"
                name="name"
                placeholder="Name"
                value={formData.name}
                onChange={handleChange}
            />
            <input
                type="email"
                name="email"
                placeholder="Email"
                value={formData.email}
                onChange={handleChange}
            />
            <button type="submit">Submit</button>
        </form>
    );
}

export default MultiInputForm;
Enter fullscreen mode Exit fullscreen mode

In this example, the formData state object holds the values for both the name and email inputs. The handleChange function updates the appropriate field based on the input's name attribute.


In this post, we explored how to handle events and manage forms in React. Understanding these concepts is crucial for creating interactive applications that respond to user input.

In our next post, we’ll dive into more advanced topics. Stay tuned!

Top comments (0)