DEV Community

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

Posted on

1

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!

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay