Open In App

Explain the purpose of the onChange event in form handling.

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Forms play a crucial role in web applications, allowing users to input data, submit information, and interact with the website. To enhance this interaction, the onChange event becomes a key player in form handling within the realm of web development.

In this article, we’ll explore the purpose and significance of the onChange event and its role in creating dynamic and responsive forms.

Prerequisites:

Why Do We Need Form Handling?

Forms act as a bridge between users and applications, providing a means for users to input data that applications can process. Form handling, therefore, involves the management of user input, validation, and the dynamic updating of the user interface based on the entered data. This is where the onChange event steps in.

  • The Essence of onChange Event: The onChange event is triggered whenever the value of an input element changes. In the context of forms, this event is particularly valuable for handling user input in real-time. Consider scenarios where you want to update a preview, perform validation, or enable/disable certain form elements based on user input. The onChange event allows you to capture these changes and respond dynamically.

Key Aspects and Applications:

  • Real-time Updates: One of the primary use cases of the onChange event is to provide users with real-time feedback as they type. For example, as a user enters their name, you can dynamically update a greeting message or validate the input without requiring a form submission.
  • Dynamic Form Elements: Based on user input in one field, you might want to show or hide other form elements. The onChange event enables you to dynamically manipulate the visibility or state of other elements, creating a more interactive and user-friendly experience.
  • Form Validation: Form validation often requires checking user input against certain criteria. With the onChange event, you can perform validation checks as users type, providing instant feedback on whether the entered data meets the required conditions.
  • Conditional Rendering: Imagine a scenario where a dropdown menu’s options change dynamically based on a selection in another dropdown. The onChange event allows you to detect changes and update the available options, ensuring a more context-aware and responsive form.

Approach to implement onChange Event:

  • State Definition: We have defined and state called “formData” with a function”setFormData” to manage the inputs given by user(‘name’, ’email’, ‘messsage’).
  • Event Handling: Two functions are created. “handleChange” which will update form state on input changes. “handleSubmit” logs form data on submission.
  • Form Structure: A form is created with name, email, message inputs and a submit button. Enclosed in a div with a “green-theme” class for styling.

Steps To Create React Application And Installing Module:

Step 1: Create a React application using the following command:

npx create-react-app newapp

Step 2: After creating your project folder(i.e. newapp), move to it by using the following command:

cd newapp

Step 3. After setting up react environment on your system, we can start creating our form in App.js file.

Project Structure:

Screenshot-(17)The dependencies in the package.json file.

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Example: Below the example to handle form:

  • A form is designed to collect user inputs such as name, email, and message.
  • The state variable “formData” is created as an object to store the user-provided information.
  • The “handleChange” function is implemented to dynamically update the “formData” state as users input values.
  • Both the “inputs” and “textarea” elements use the “onChange” event, triggering the “handleChange” function.
  • The “handleChange” function utilizes the “setFormData” method to instantly update the state with the changing input values.
  • A “handleSubmit” function is established to display the collected “formData” when the “Submit” button is clicked.
  • Essentially, “onChange” is employed to monitor and respond to changes in user input by invoking the “handleChange” function, facilitating real-time updates to the form data state.

Javascript




// App.js
 
import React, { useState } from "react";
import "./App.css";
 
const App = () => {
    const [formData, setFormData] = useState({
        name: "",
        email: "",
        message: "",
    });
 
    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData({
            ...formData,
            [name]: value,
        });
    };
 
    const handleSubmit = (e) => {
        e.preventDefault();
        console.log("Form submitted:", formData);
    };
 
    return (
        <div className="green-theme">
            <form onSubmit={handleSubmit}>
                <label htmlFor="name">Name:</label>
                <input
                    type="text"
                    id="name"
                    name="name"
                    value={formData.name}
                    onChange={handleChange}
                />
 
                <label htmlFor="email">Email Address:</label>
                <input
                    type="email"
                    id="email"
                    name="email"
                    value={formData.email}
                    onChange={handleChange}
                />
 
                <label htmlFor="message">Message:</label>
                <textarea
                    id="message"
                    name="message"
                    value={formData.message}
                    onChange={handleChange}
                />
 
                <button type="submit">Submit</button>
            </form>
        </div>
    );
};
 
export default App;


CSS




.App {
    text-align: center;
}
 
.green-theme {
    background-color: #4caf50;
    padding: 20px;
    border-radius: 8px;
    width: 300px;
    margin: auto;
}
 
form {
    display: flex;
    flex-direction: column;
}
 
label {
    margin-bottom: 8px;
    color: #ffffff;
}
 
input,
textarea {
    padding: 8px;
    margin-bottom: 16px;
    border: 1px solid #ffffff;
    border-radius: 4px;
}
 
button {
    background-color: #ffffff;
    color: #4caf50;
    padding: 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}
 
button:hover {
    background-color: #e7e7e7;
}


Start your application using the following command:

npm start

Output:

Screenshot-(26)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads