Unit 3
Unit 3
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.
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>
);
}
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>
);
}
5
Page
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
</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('');
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>
</>
);
}
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.
Example -
import React, { useState } from "react";
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>
);
};
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';
return (
<button onClick={handleClick}>Click Me</button>
);
};
Example 2
import React, { useState } from 'react';
return (
<div>
<p>Button clicked {count} times</p>
<button onClick={handleClick}>Click Me</button>
</div>
);
};
Example 1
import React, { Component } from 'react';
class ClassEvent extends Component {
handleClick() {
alert('Button Clicked!');
}
render() {
return (
<button onClick={this.handleClick}>Click Me</button>
);
}
}
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 AgeVerificationForm;
Page
Example 2 -
import React, { useState } from "react";
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
Example 2 - onKeyUp
import React, { useState } from "react";
return (
<div>
Page
Example 1 -
import React from "react";
return (
<button onClick={() => handleClick("Hello, React!")}>
Click Me
</button>
);
};
Example 2 -
import React, { useState } from "react";
return (
<div>
<input type="text" onChange={(e) => setMessage(e.target.value)} />
<button onClick={() => handleClick(message)}>Click Me</button>
</div>
);
};
20
Page