0% found this document useful (0 votes)
10 views21 pages

LECTURE 14 Forms Handling

This document covers handling forms and user input in React, focusing on form submissions, validations, and the differences between controlled and uncontrolled components. It outlines key concepts, attributes, and event handling related to forms, emphasizing the importance of validation for data accuracy and user experience. The session concludes with a basic example of a React form and prepares for the next topic on fetching data from APIs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views21 pages

LECTURE 14 Forms Handling

This document covers handling forms and user input in React, focusing on form submissions, validations, and the differences between controlled and uncontrolled components. It outlines key concepts, attributes, and event handling related to forms, emphasizing the importance of validation for data accuracy and user experience. The session concludes with a basic example of a React form and prepares for the next topic on fetching data from APIs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Handling Forms and

User Input in React


Session No.: 14
Course Name: Full Stack Development Using React and Node.JS
Course Code: E1UA207B
Engaging Questions
“ When was the last time you filled a form online — maybe
for login, signup, or feedback?”

Reflection: Everyone has filled some form.

“ What did you notice when you left a field blank or entered
a wrong email?”

Reflection: a message appears which highlights the


importance of form validation.
Learning Outcomes:

1.Handle form submissions and validations in React


2.Analyze controlled and uncontrolled components in
forms.
Outline:
• What are Forms in React?
• Key terms in handling form
• Form elements
• Form Attributes
• Activity
• Types of Form
• Controlled and Uncontrolled components
• Event handling in Forms
• Form Validation
What are Forms
in React?
In React, forms are used to collect user input. They
can handle various data types and are key for
managing user interaction and data submission.
Unlike traditional HTML, React uses controlled
components where form elements like <input>,
<textarea>, and <select> get their values from the
component’ s state.
React also supports uncontrolled components
using ref, but controlled components are more
common for dynamic forms.
Key terms in handling form
Term Explanation
Process of collecting user input, validating it, and
Form Handling taking action (like submitting or displaying error
messages).

An input element whose value is controlled by React


Controlled Component
state using useState.

A built-in React function used to store and update state


useState Hook
in functional components.

React captures user actions (like typing or clicking)


Event Handling through event listeners like onChange, onClick,
onSubmit.

Prevents the default action of the form (like reloading


e.preventDefault()
the page) when the submit button is clicked.

Ensuring the user input meets certain criteria (e.g.,


Validation valid email, password length) before accepting or
submitting it.

We use another state (like errors) to store and display


Error State
error messages conditionally.
Form Elements
Form elements are the individual components used inside a
form to collect user input.

Element Purpose Example

<form> Container for all input elements <form>...</form>

Takes user input (text, number, email,


<input> <input type="text" />
etc.)
<textarea> Multi-line text input <textarea></textarea>
<select><option>One</option></select
<select> Drop-down menu
>

<option> Defines each item in a drop-down <option value="1">One</option>

<label> Describes the input field <label>Email:</label>

<button
<button> Used to submit or reset the form
type="submit">Submit</button>

<legend> Title for grouped fields <legend>User Info</legend>

<input type="checkbox"> Selects one or more options <input type="checkbox" />

<input type="radio"> Selects one from many options <input type="radio" />
Form Attributes
A t tr ib u tes in for m han dlin g are p roperties added to H T M L f orm elem ents ( like < inp ut> , < form > , < tex tarea> ,
etc.) that define th eir b ehav ior, app ear ance, an d how data is collected , v alidated , or su bm itted .

Attribute Purpose / Description Example


Defines the input type (text, email,
type <input type="email" />
password, etc.)
Name of the field, used during
name <input name="username" />
submission or data handling
The current value (used in
value <input value={email} />
controlled components in React)
Event handler when input value <input onChange={handleChange}
onChange
changes />
Event handler when form is
onSubmit <form onSubmit={handleSubmit}>
submitted
Text shown in input when it’ s
placeholder <input placeholder="Enter name" />
empty
Makes a field mandatory (HTML5
required <input required />
validation)
Used in uncontrolled components
defaultValue <input defaultValue="John" />
(initial value)
Example of a simple React
form
import React from "react";
function App() {
return (
<form>
<label>
Username:
<input type="text" name="username" />
</label>
<label>
Password:
<input type="password" name="password" />
</label>
<input type="submit" value="Submit" />
</form>
);}
Activity: Think, Pair and Share

Task
• List all the HTML elements in the code.
• Under each element, identify all the attributes.
• Mention the purpose of each attribute (in one sentence).
Types of Forms
There are two main types of forms in React: controlled components,
where form data is managed by React state, and uncontrolled
components, where data is handled by the DOM.
Controlled Components (Recommended)
A controlled component in React is a form element (like input or textarea) whose
value is fully controlled by React's state, not by the DOM itself.
Each input element has its value bound to state and triggers updates via change
handlers. i.e., instead of the input box holding the data directly, React's state (like
memory) keeps track of what’ s written.

Here, value={name} means React controls what’ s in the box,


and onChange lets React update its memory (state) every time you type.

What is happening?
• The input’ s value is always taken from name (React’ s state).
• When you type, onC hange updates the name state.
• React re-renders with the new value
Uncontrolled Components
In uncontrolled component, Value is stored inside the input box itself (like normal
HTML).
Here, DOM handles the input values, and React accesses them using ref

What’ s happening?

• The input manages its own value internally — just like plain HTML.
• React does not know what’ s being typed.
• There is no value or onChange.
• If you want to get the value later (say, when a button is clicked), you need a ref.
.

Comparison
Feature Controlled Form Uncontrolled Form

Real-time validation ✅ Yes ❌ No

State Management Via useState Via ref

Best For Most React forms Simple, static forms

Code Complexity Medium Low


.

Event Handling in Forms


Event handling in forms refers to the
process of responding to user interactions
with form elements, such as:

• Typing in a text field


• Selecting an option from a dropdown
• Clicking a button
• Submitting the form
.

Key Concepts in Event Handling

Concept Explanation

Triggered when the value of an input field changes (e.g., typing in


onChange event
a textbox).

Triggered when the user submits the form (e.g., pressing a


onSubmit event
button).

Prevents the browser's default behavior (e.g., page refresh on


preventDefault()
submit).

Controlled Components Input fields whose values are managed via state (React specific).
.

Form Validation
Form validation ensures users enter data in the correct format and meet all
the input requirements (like email format, required fields, length, etc.)

Example of Validations You Can Add:

Validation code

Email Input Validation: <input type="email" required />


Number Input with Min/Max <input type="number“ min="18“ max="60”
required />
Password with Min Length <input type="password“ minLength="8“
required />
.

Why Form Validation is important?


Reason Explanation
Ensures users input the right kind of data (e.g., valid email,
Data Accuracy
number, etc.).

Security Prevents malicious data like script injections or invalid requests.

Backend Reliability Saves only clean and expected data to the server or database.

Error Prevention Reduces bugs and system crashes caused by unexpected input.

Helps users fix mistakes with helpful messages (like “ email


User Guidance
required” ).

Users know immediately if something's wrong— no need to wait


Improves UX
for submission.
.

A basic React code of Login Form using a controlled component


approach
Conclusions

In summary, understanding forms in React is crucial for creating


interactive web applications. Mastery of controlled and
uncontrolled components, along with effective validation, greatly
enhances user experience.
Next Session

Fetching Data from APIs

You might also like