0% found this document useful (0 votes)
25 views20 pages

Unit 3

The document discusses React JS forms, emphasizing the difference between controlled and uncontrolled forms, where controlled forms manage data via component state and uncontrolled forms rely on the DOM. It outlines best practices for form handling and validation in React, including the use of libraries like Formik and React Hook Form. Additionally, it provides examples of form components and validation techniques to enhance user experience and data accuracy.
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)
25 views20 pages

Unit 3

The document discusses React JS forms, emphasizing the difference between controlled and uncontrolled forms, where controlled forms manage data via component state and uncontrolled forms rely on the DOM. It outlines best practices for form handling and validation in React, including the use of libraries like Formik and React Hook Form. Additionally, it provides examples of form components and validation techniques to enhance user experience and data accuracy.
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/ 20

T.Y.B.C.A.

[Sem 6] BCA 604 (A) Web Development Technology-IV


(Web Developments with React.js and Node.js)

Unit - 3
React JS Forms And UI

React Forms -
Forms play a crucial role in web applications as they allow users to input and
submit data, such as login credentials, registration details, and search queries.
In traditional HTML, forms are managed by the Document Object Model (DOM),
where the browser handles user input and updates the form elements
accordingly.
However, in React, form handling is component-driven, meaning the form data
is managed within the component's state rather than the DOM. This approach
ensures better control over the form elements and allows dynamic updates
based on user interactions.
In React, when a user enters data into a form field, the component’s state is
updated in real-time. This is achieved using the useState Hook, which keeps
track of input values and provides a structured way to handle changes. The
onChange event handler is used to capture user input and update the state
accordingly. Since React follows a unidirectional data flow, the state acts as the
single source of truth, ensuring consistency across the application. This
approach makes form handling more predictable, improves performance, and
allows for features like form validation, conditional rendering, and controlled
component behavior.
By efficiently managing form data, React ensures a smooth and responsive user
experience in web applications.

Types of Forms in React


In React, forms can be categorized into two types: Controlled Forms and
Uncontrolled Forms, based on how the form data is managed. React provides
flexibility in handling user input, making forms more interactive and efficient.
The main difference between these two types is whether the form data is
1

controlled by React's state or the DOM.


Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

1. Controlled Forms:
In Controlled Forms, React manages the form data using the component's state.
Whenever a user types in an input field, the state is updated, and the form
elements always reflect the latest state value. This approach ensures better
control over user input and allows features like validation, conditional
rendering, and data manipulation before submission. The useState Hook is
commonly used in controlled forms to track and update input values
dynamically.
Steps to Create a Controlled Form:
• Use the useState hook to create state variables for each input field.
• Bind the input field's value to the state variable.
• Use the onChange event to update the state when the user types.
Example:
import React, { useState } from 'react';

function SimpleForm() {
const [name, setName] = useState('');
const handleChange = (e) => {
setName(e.target.value); // Updates state with input value
};
const handleSubmit = (e) => {
e.preventDefault(); // Prevents page reload
alert("Hello .... " + name);
};
return (
<form onSubmit={handleSubmit}>
Name:<input type="text" value={name} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
}

export default SimpleForm;


2
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

2. Uncontrolled Forms:
Uncontrolled Forms rely on the DOM to manage input values instead of React’s
state. Here, the input fields store their own values, and React accesses them
when needed using refs. This method is useful when integrating with third-party
libraries or when form handling does not require frequent state updates. Since
React does not re-render the component on each input change, uncontrolled
forms may offer better performance in some cases. However, they provide less
control over user input compared to controlled forms.
Steps to Create an Uncontrolled Form:
• Use the useRef hook to access the input value directly from the DOM.
• No need to update the state on every change.

Example:
import React, { useRef } from 'react';

function UncontrolledForm() {
const inputRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
alert(`Hello..., ${inputRef.current.value}!`);
};
return (
<form onSubmit={handleSubmit}>
Name: <input type="text" ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
}

export default UncontrolledForm;


3
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

Differences Between Controlled and Uncontrolled Forms

Feature Controlled Form Uncontrolled Form


Data Handling Managed by React state Managed by the DOM
(useState). (useRef).
Input Value Stored in the component’s Stored directly in the input
state. field.
Control Over React has full control over The input field manages its
Data the input. own value.
State Updates Updates the state on every Does not update the state on
change. every change.
Performance May cause more re-renders More efficient as it avoids
due to state updates. frequent re-renders.
Event Uses onChange to update Uses ref to access the input
Handling state. value when needed.
Code Slightly more code Less code
Complexity
Best Used For When validation, When minimal React control is
conditional rendering, or needed, such as integrating
controlled behavior is with third-party libraries.
required.

Best Practices for React Forms


1. Always use onSubmit on the <form> tag to handle form submission.
2. Use controlled components for better control and validation.
3. Validate inputs before submission to avoid errors.
4. Use libraries like Formik or React Hook Form for complex forms.
5. Keep Forms User-Friendly
4
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

Common Form Elements in React


React supports various form elements to collect user input. Here are some
commonly used form elements:
1. Text Input (<input type="text">) – Used for single-line text input.
2. Password Input (<input type="password">) – Hides user input for
passwords.
3. Email Input (<input type="email">) – Accepts and validates email
addresses.
4. Number Input (<input type="number">) – Accepts numeric values only.
5. Radio Buttons (<input type="radio">) – Allows users to select one option
from a group.
6. Checkbox (<input type="checkbox">) – Enables multiple selections.
7. Text Area (<textarea>) – Used for multi-line text input.
8. Dropdown Select (<select>) – Provides a list of options for users to choose
from.
9. Date Picker (<input type="date">) – Allows users to select a date.
10.File Upload (<input type="file">) – Enables users to upload files.
11.Submit Button (<button type="submit">) – Triggers form submission.
12.Reset Button (<button type="reset">) – Clears all input fields in the form.

5
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

Control Input Elements


In React, controlled input elements are form inputs (such as text fields,
checkboxes, and radio buttons) whose values are controlled by the component’s
state. Instead of letting the browser handle the input values, React manages
them using the useState Hook.
Whenever a user types in an input field, an event handler (onChange) updates
the state with the new value. Since React controls the data, it allows easy
validation, real-time updates, and dynamic behavior based on user input.
In React, controlled input elements are a way to manage form inputs using
state. This means that the value of the input field is controlled by React, rather
than being managed by the DOM. Controlled inputs are a key concept in React
forms and provide better control over user data.
How Controlled Inputs Work
1. State Management: The value of the input field is stored in the
component's state. For example, if you have a text input, its value is tied
to a state variable using the useState Hook.
2. Event Handling: When the user types or changes the input, an onChange
event handler updates the state with the new value. This ensures that the
input field always reflects the current state.
3. Single Source of Truth: Since the input value is stored in the state, it
becomes the "single source of truth" for that input. This makes it easier
to validate, manipulate, or submit the data.

Example 1:
import React, { useState } from 'react';
function ControlledInput() {
const [name, setName] = useState('');
const handleChange = (e) => {
setName(e.target.value);
};
return (
<div>
<input type="text" value={name} onChange={handleChange} />
6
Page

<p>Entered Name: {name}</p>

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

</div>
);
}
export default ControlledInput;

Example 2:
import React, { useState } from 'react';

function AdditionForm() {
const [num1, setNum1] = useState('');
const [num2, setNum2] = useState('');
const [result, setResult] = useState('');

const handleSubmit = (e) => {


e.preventDefault();
const sum = parseFloat(num1) + parseFloat(num2);
setResult(sum);
};

return (
<>
<h1>Simple Addition Form</h1>
<form onSubmit={handleSubmit}>
<div>
Number 1: <input type="number" value={num1} onChange={(e) =>
setNum1(e.target.value)} required />
Number 2: <input type="number" value={num2} onChange={(e) =>
setNum2(e.target.value)} required />
</div>
<button type="submit">Add</button>
</form>
<h2>Result: {result}</h2>
</>
);
}

export default AdditionForm;


7
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

React JS Form Validations


Form validation in React is the process of checking user inputs before submitting
the form. It helps prevent errors, ensures data accuracy, and improves user
experience. In traditional HTML forms, validation is handled by the browser, but
in React, it is managed using state and event handlers.
In React, form validation can be done using simple JavaScript conditions or with
the help of external libraries like Formik and React Hook Form. Common
validations include checking if a field is empty, ensuring correct email format,
and setting minimum or maximum character limits. The validation logic runs
when the user types in an input field or submits the form. If the input is incorrect,
an error message is displayed, guiding the user to enter the correct data.
By implementing proper form validation, developers can prevent invalid data
from being submitted, making applications more secure and user-friendly.
In ReactJS, form validation can be implemented using various approaches,
including controlled components, uncontrolled components, and third-party
libraries like Formik and React Hook Form.
Here are the types of form validations in ReactJS:
1. Client-Side Validation
o Performed in the browser before sending data to the server.
o Uses JavaScript to validate inputs in real-time.
o Examples: Required fields, email format, password strength.
2. Server-Side Validation
o Performed on the backend after the form is submitted.
o Ensures security by preventing malicious inputs (e.g., SQL Injection,
XSS).
o Used when client-side validation is not sufficient.
3. Real-Time (On-Change) Validation
o Checks input validity as the user types.
o Provides instant feedback, like password strength indicators.
8
Page

o Implemented using React state updates.

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

4. Synchronous Validation
o Performed immediately without waiting for external data.
o Uses built-in validation logic within React components.
o Example: Checking if a password meets length requirements.
5. Asynchronous Validation
o Involves an external process, such as API calls to validate data.
o Example: Checking if a username or email is already registered.
o Uses fetch or axios to validate against a backend server.
6. Schema-Based Validation
o Uses libraries like Yup with Formik or React Hook Form.
o Allows defining validation rules in a structured way.
7. Custom Validation
o Developers define their own logic for validation.
o Example: Checking if a credit card number follows Luhn's algorithm.

Best Practices for Form Validation in ReactJS:


1. Provide Clear Error Messages: Help users understand what went wrong.
2. Use Real-Time Validation for Better UX: Validate fields as the user types.
3. Combine Client-Side and Server-Side Validation: Ensure security and
usability.
4. Leverage Libraries: Use libraries like Yup, Formik, or React Hook Form to
simplify validation.
5. Test Thoroughly: Ensure all validation scenarios are covered.
9
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

Example -
import React, { useState } from "react";

const EmailForm = () => {


const [email, setEmail] = useState("");
const [error, setError] = useState("");
const validateEmail = (email) => {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email); // Returns true or false
};

const handleSubmit = (e) => {


e.preventDefault();
if (!validateEmail(email)) {
setError("Invalid email format");
return;
}
setError("");
setEmail("");
};

return (
<form onSubmit={handleSubmit}>
<div>
Email: <input type="text" id="email" value={email}
onChange={(e) => setEmail(e.target.value)} placeholder="Enter your email" />
</div>
{error && <p style={{ color: "red" }}>{error}</p>}
<button type="submit">Submit</button>
</form>
);
};

export default EmailForm;


10
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

React Events
Events in React are similar to events in JavaScript. They allow developers to
respond to user interactions like clicking a button, typing in a text field,
submitting a form, or hovering over an element. React events are handled using
event handlers, which are functions that execute when an event occurs.
Key Features of React Events:
• SyntheticEvent: React wraps native browser events into a SyntheticEvent
object. This ensures consistent behavior across all browsers.
• CamelCase Naming: Event names are written in camelCase (e.g., onClick,
onChange).
• Event Handlers: Event handlers are passed as functions (not strings) to
React components.
• Automatic Binding: In class components, this is automatically bound to
event handlers. In functional components, you can use arrow functions
or useCallback to avoid binding issues.
• Instead of using return false to prevent default behavior, React uses
event.preventDefault().

Example 1
import React from 'react';

const EventExample = () => {


const handleClick = () => {
alert('Button Clicked!');
};

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

export default EventExample;


11
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

Example 2
import React, { useState } from 'react';

const ClickHandler = () => {


const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};

return (
<div>
<p>Button clicked {count} times</p>
<button onClick={handleClick}>Click Me</button>
</div>
);
};

export default ClickHandler;

Handling Events with Class Components


Before the introduction of React Hooks, events in React were handled using
class components (Older Approach) and the this keyword. However, class
components come with certain limitations:
• They require explicit binding of event handlers in the constructor, e.g.,
this.handleClick = this.handleClick.bind(this);
• They involve more boilerplate code, making them less concise and
harder to maintain.
• React recommends using function components with hooks (useState,
useEffect) for new applications, as they simplify event handling and
improve performance.
12
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

Example 1
import React, { Component } from 'react';
class ClassEvent extends Component {
handleClick() {
alert('Button Clicked!');
}
render() {
return (
<button onClick={this.handleClick}>Click Me</button>
);
}
}

export default ClassEvent;

Example 2
import React, { Component } from 'react';
class ClickHandler extends Component {
constructor() {
super();
this.state = { count: 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Button clicked {this.state.count} times</p>
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}

export default ClickHandler;


13
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

Common React Events:


Event Type React Event Name Description
Click onClick Triggered when an element is
clicked.
Change onChange Triggered when an input value
changes.
Submit onSubmit Triggered when a form is submitted.
Mouse onMouseEnter, Triggered when the mouse
Events onMouseLeave enters/leaves an element.
Keyboard onKeyDown, onKeyUp Triggered when a key is
Events pressed/released.
Focus Events onFocus, onBlur Triggered when an element
gains/loses focus.

Examples: Handling Events in React


1. Click Event (onClick):
import React, { useState } from "react";

const ToggleText = () => {


const [text, setText] = useState("Hello, Welcome!");
const toggleMessage = () => {
setText(text === "Hello, Welcome!" ? "Have a Great Day!" : "Hello, Welcome!");
};
return (
<div style={{ textAlign: "center", padding: "20px" }}>
<h2>{text}</h2>
<button onClick={toggleMessage} style={{ fontSize: "16px" }}>
Toggle Message
</button>
</div>
);
};
14

export default ToggleText;


Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

2. Change Event (onChange):


import React, { useState } from "react";
const ColorPicker = () => {
const [color, setColor] = useState("#ff0000");
return (
<div style={{ textAlign: "center", padding: "20px", backgroundColor: color }}>
<h2>Pick a Color:</h2>
<input type="color" value={color} onChange={(e) => setColor(e.target.value)} />
<p>Selected Color: {color}</p>
</div>
);
};
export default ColorPicker;

3. Submit Event (onSubmit):


Example 1 -
import React, { useState } from "react";
const AgeVerificationForm = () => {
const [age, setAge] = useState("");
const [message, setMessage] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
if (age >= 18) {
setMessage("You are eligible to proceed!");
} else {
setMessage("Sorry, you must be at least 18 years old.");
}
};
return (
<div>
<h3>Age Verification</h3>
<form onSubmit={handleSubmit}>
<input type="number" value={age} onChange={(e) => setAge(e.target.value)} />
<button type="submit">Submit</button>
</form>
{message && <h4>{message}</h4>}
</div>
);
15

};
export default AgeVerificationForm;
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

Example 2 -
import React, { useState } from "react";

const AgeVerificationForm = () => {


const [dob, setDob] = useState("");
const [message, setMessage] = useState("");
const calculateAge = (dob) => {
const birthDate = new Date(dob);
const today = new Date();
let age = today.getFullYear() - birthDate.getFullYear();
const monthDiff = today.getMonth() - birthDate.getMonth();
const dayDiff = today.getDate() - birthDate.getDate();
// Adjust age if the birthday hasn't occurred yet this year
if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
age -= 1;
}
return age;
};
const handleSubmit = (e) => {
e.preventDefault(); // Prevent page reload
const age = calculateAge(dob);
if (age >= 18) {
setMessage(`You are ${age} years old. You are eligible!`);
} else {
setMessage(`You are ${age} years old. You must be at least 18.`);
}
};
return (
<div>
<h3>Age Verification</h3>
<form onSubmit={handleSubmit}>
<label>Enter your Date of Birth:</label>
<input type="date" value={dob} onChange={(e) => setDob(e.target.value)}
required />
<button type="submit">Verify Age</button>
</form>
{message && <h4>{message}</h4>}
</div>
);
};
16

export default AgeVerificationForm;


Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

4. Mouse Events (onMouseEnter, onMouseLeave):


import React, { useState } from "react";
const MouseExample = () => {
const [isHovered, setIsHovered] = useState(false);
return (
<div
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
style={{
padding: "20px",
backgroundColor: isHovered ? "lightblue" : "white",
border: "1px solid black",
}}
>
{isHovered ? "Mouse is over me!" : "Hover over me!"}
</div>
);
};

export default MouseExample;

5. Keyboard Events:
Example 1 - onKeyDown
import React, { useState } from "react";
const KeyPressDisplay = () => {
const [keyPressed, setKeyPressed] = useState("");
const handleKeyDown = (e) => {
setKeyPressed(`You pressed: ${e.key}`);
};
return (
<div>
<h3>Press Any Key</h3>
<input type="text" onKeyDown={handleKeyDown} placeholder="Press a key" />
<h2>{keyPressed}</h2>
</div>
);
};
export default KeyPressDisplay;
17
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

Example 2 - onKeyUp
import React, { useState } from "react";

const UppercaseConverter = () => {


const [text, setText] = useState("");
const handleKeyUp = (e) => {
setText(e.target.value.toUpperCase());
};
return (
<div>
<h3>Convert to Uppercase</h3>
<input type="text" onKeyUp={handleKeyUp} placeholder="Type something..." />
<p>Uppercase: {text}</p>
</div>
);
};

export default UppercaseConverter;

Example 3 - Typing Speed Tracker


import React, { useState, useEffect } from "react";

const TypingSpeedTracker = () => {


const [charCount, setCharCount] = useState(0);
const [startTime, setStartTime] = useState(null);
const [speed, setSpeed] = useState(0);
const handleKeyDown = () => {
if (charCount === 0) {
setStartTime(Date.now()); // Start timer when first key is pressed
}
setCharCount((prevCount) => prevCount + 1);
};
useEffect(() => {
if (charCount > 0) {
const elapsedTime = (Date.now() - startTime) / 1000; // Time in seconds
setSpeed((charCount / elapsedTime).toFixed(2)); // Calculate speed (chars/sec)
}
}, [charCount]);
18

return (
<div>
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

<h3>Typing Speed Tracker</h3>


<input type="text" onKeyDown={handleKeyDown} placeholder="Start typing" />
<p>Characters Typed: {charCount}</p>
<p>Typing Speed: {speed} chars/sec</p>
</div>
);
};

export default TypingSpeedTracker;

Passing Arguments to Event Handlers:


If you need to pass additional arguments to an event handler, use an arrow
function inside the event attribute. This ensures the function is not executed
immediately but only when the event occurs. The arrow function allows passing
dynamic values while still receiving the event object if needed.

Example 1 -
import React from "react";

const ArgumentExample = () => {


const handleClick = (message) => {
alert(message);
};

return (
<button onClick={() => handleClick("Hello, React!")}>
Click Me
</button>
);
};

export default ArgumentExample;


19
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal


T.Y.B.C.A. [Sem 6] BCA 604 (A) Web Development Technology-IV
(Web Developments with React.js and Node.js)

Example 2 -
import React, { useState } from "react";

const DynamicArgumentExample = () => {


const [message, setMessage] = useState("Hello, React!");
const handleClick = (msg) => {
alert(msg);
};

return (
<div>
<input type="text" onChange={(e) => setMessage(e.target.value)} />
<button onClick={() => handleClick(message)}>Click Me</button>
</div>
);
};

export default DynamicArgumentExample;

20
Page

Compiled (from Open Source) by - Prof. Piyush S. Agrawal

You might also like