0% found this document useful (0 votes)
2 views

ReactJs Unit - III

Unit III covers handling events and forms in React, detailing form components like checkboxes and text fields, and the difference between controlled and uncontrolled components. It explains form submission, validation techniques using Formik and Yup, and various methods for styling and animating components. Additionally, it discusses event handling, including common events and key events, along with the concept of Synthetic Events for cross-browser compatibility.

Uploaded by

Akash Kale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

ReactJs Unit - III

Unit III covers handling events and forms in React, detailing form components like checkboxes and text fields, and the difference between controlled and uncontrolled components. It explains form submission, validation techniques using Formik and Yup, and various methods for styling and animating components. Additionally, it discusses event handling, including common events and key events, along with the concept of Synthetic Events for cross-browser compatibility.

Uploaded by

Akash Kale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Unit - III

Handling Events and Forms

❖ Lists of Form components

● Checkbox
● Button
● Radio
● TextField
● Select
● Button Group
● Radio Group

❖ Setup Controlled and Uncontrolled form components

● Controlled components rely on React state to manage the form data, while
● uncontrolled components use the DOM itself to handle form data.
● In a controlled component, form data is handled by a React component.
● The alternative is uncontrolled components, where form data is handled
by the DOM itself.

Controlled Component Uncontrolled Component

The component is under control of the Components are under the control of
component’s state. DOM.
These components are predictable as are Are Uncontrolled because during the
controlled by the state of the component. life cycle methods the data may loss

Internal state is not maintained Internal state is maintained

It accepts the current value as props We access the values using refs

Controlled by the parent component. Controlled by the DOM itself.

Have better control on the form data and Has very limited control over form
values values and data

❖ Control Input elements

● Controlled components are form elements (like input , textarea , or select )


that are managed by React state.
● A controlled element is an input form element whose value is controlled by
the React component’s state.
● Unlike uncontrolled elements, where the DOM itself manages the state of
the input, controlled elements allow React to maintain control over the
input’s value.
● controlled input is an input that gets its value from a single source of truth.
❖ Form Submission and Validation

● You can control the submit action by adding an event handler in the
onSubmit attribute for the <form>.
Example -

import { useState } from "react";


import ReactDOM from 'react-dom/client';

function MyForm() {
const [name, setName] = useState("");

const handleSubmit = (event) => {


event.preventDefault();
alert(`The name you entered was: ${name}`);
}

return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<input type="submit" />
</form>
)
}

● It is the event configured for “form” element.


● It fires up the functionality when form is submitted.

❖ Validation
● Validation is the process of verifying user input.
● Validation is required to ensure that contractionary and unauthorized data is not
get stored into database.
● Validation can be handled manually or by using pre-defined library functions and
properties.
● Formik supports synchronous and asynchronous validations.
● Formik handles validation at 2 levels
○ Formstate validation / Form-level validation
○ Inputstate validation / Field-level validation
● “Yup” is used for Schema based validation.
● Formik uses various methods/events for validating the values
○ After Change events/methods
■ handleChange
■ setFieldValue
■ setValues
■ After Blur events/methods
● handleBlur
● setTouched
● setFieldTouched
■ After Submit events/methods
● handleSubmit
● submitForm
Ex:
import React from 'react';
import ReactDOM from 'react-dom';
import {useFormik} from 'formik';
const validateProduct = productData => {
const errors = {}
if(!productData.Name) {
errors.Name = 'Product Name Required';
} else if(productData.Name.length<4) {
errors.Name = 'Name too short..Min 4 required';
}

if(!productData.Price) {
errors.Price = 'Product Price Required';
}

if(!productData.Code) {
errors.Code = 'Product Code Required';
} else if (!/[A-Z]{3}[0-9]{2}/.test(productData.Code)) {
errors.Code = 'Invalid Code..';
}
return errors;
}
const RegisterProductComponent = () => {
const formik = useFormik({
initialValues: {
Name: '',
Price: '',
Code: ''
},
validate: validateProduct,
onSubmit: values => {
alert(JSON.stringify(values));
}
})

return(
<div>
<h2>Register Product</h2>
<form onSubmit={formik.handleSubmit}>
<div className="form-group">
<label>Name</label>
<div>
<input name="Name" onBlur={formik.handleBlur}
onChange={formik.handleChange} value={formik.values.Name}
type="text" />
<div className="text-danger"> {(formik.touched.Name &&
formik.errors.Name)?formik.errors.Name:null} </div>
</div>
</div>
<div className="form-group">
<label>Price</label>
<div>
<input type="text" onBlur={formik.handleBlur}
onChange={formik.handleChange} name="Price"
value={formik.values.Price} />
<div className="text-danger"> {(formik.touched.Price &&
formik.errors.Price)?formik.errors.Price:null} </div>
</div>
</div>
<div class="form-group">
<label>Code</label> <div>
<input onBlur={formik.handleBlur} onChange={formik.handleChange}
name="Code" value={formik.values.Code} type="text" />
<div className="text-danger"> {(formik.touched.Code &&
formik.errors.Code)?formik.errors.Code:null} </div>
</div>
</div>
<div className="form-group">
<button>Register</button>
</div>
</form>
</div>
)
}
ReactDOM.render(
<RegisterProductComponent />,
document.getElementById("root")
);
export default RegisterProductComponent;

❖ how to set default values on all formats of Input elements

const [firstName, setFirstName] = React.useState("Ankurito");

❖ writing Styles
● Styles provide attributes to make HTML more interactive and
responsive.
● Styles can be configured using
○ Inline Styles
○ Embedded Styles
○ Cascading Style Sheets (CSS)
○ Styling Libraries [Radium, React Materials]
Inline Styles
● Styles are defined for every element in component individually by
using “style” prop.
● You can pass any dynamic value into “style” attribute so that it can
change dynamically according to state and situation.
● Ex: JavaScript
<div id=”container” style=”background-color:red”>
document.getElementById(“container”).style.backgrou ndColor = “red”;
● React JS also uses “camel case” for configuring the styles
dynamically.
● Dynamic styles are defined by using a style object.

Syntax: Applying styles using Style object

const styleObject = { styleAttribute: ‘value’, styleAttribute: ‘value }

<div style={styleObject}</div>

Syntax: Apply attributes directly to element

<div style={{attribute:value,attribute:value}}></div>

Embedded Styles

● Embedded styles are defined in “HTML” page by


using <style> element.
● It can embed a set of styles, which are allowed to
reuse across elements.

Index.html

<style>
dt {
background-color: gray;
color:white;
padding:5px;
}
</style>
CSS

● Styles are maintained in a separate CSS file and are


linked to your document.
● You can also import CSS files into component and
use.
● If you are using a modular system for react
application then you have to import the CSS files
into component.

Syntax:
app.css
selector {
attribute: value
}
app.js
import “./app.css”
● If you are not using a modular system then you
have to link all your CSS files into index.html
<link rel=”stylesheet” href=”../src/app.css”>

❖ Animations overview
● React Spring. React Spring is an animation library that uses spring physics to
create smooth animations for all types of UI. …
● React Motion. React Motion is a popular open-source animation library for React
that simplifies the process of creating realistic animations. …
● Animations in ReactJS can improve the user experience and make an application
more engaging and interactive. They can be used to:
● Provide feedback for user actions
● Guide users' attention
● Maintain continuity when changing views
● Make the application more intuitive
● Show the loading status of a component
● Transition between routes
● Confirm form submission
Here are some ways to create animations in ReactJS:

● CSS: Add classes to HTML tags


● GreenSock: A powerful animation platform
● React-transition-group: An add-on component for basic CSS animations and
transitions
● React-animations: Implements all animations from animate.css
● React Reveal: An animation framework for React
● THREE.js: A cross-browser JavaScript library that allows users to create and
display animated 3D computer graphics in a web browser
● Framer Motion: A library that allows users to add animations by prepending
motion to any default HTML element

❖ Event
What is Event?
● Event is a message sent by sender to its subscriber in order to notify the change.
● Event follows “Observer”, which is a communication design pattern.
● Event uses “Delegate mechanism” – Function Pointer.
❖ Event Binding

● You can bind the event in initialization phase of


component “constructor()”
● You can bind the event in “event handler” of DOM
element.
● You can bind the event without using “bind()”
method, you have to uses a call back technique to return the event and bind to
the element.
● You can use the event return value and bind to event by using anonymous
technique.

Ex: Constructor
App.js
class Product extends React.Component
{
constructor(props){
super(props);
this.state = {
msg : 'Select Database Operation'
}
this.InsertClick = this.InsertClick.bind(this);
}
InsertClick(){
this.setState({
msg: 'Record Inserted'
})
}
render(){
return(
<>
<div className="btn-group">
<button onClick={this.InsertClick} className="btn
btn-primary">Insert</button>
</div>
<h2 className="text-center">{this.state.msg}</h2>
</>
)
}
}
class MainContent extends React.Component
{
render(){
return (
<div className="container-fluid">
<h3>Event Handling</h3>
<Product />
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Ex: DOM Event Handler
App.js
class Product extends React.Component
{
constructor(props){
super(props);
this.state = {
msg : 'Select Database Operation'
}
}
InsertClick(){
this.setState({
msg: 'Record Inserted'
})
}
render(){
return(
<>
<div className="btn-group">
<button onClick={this.InsertClick.bind(this)}
className="btn btn-primary">Insert</button>
</div>
<h2 className="text-center">{this.state.msg}</h2>
</>
)
}
}
class MainContent extends React.Component
{
render(){
return (
<div className="container-fluid">
<h3>Event Handling</h3>
<Product />
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Ex: Without bind() method
class Product extends React.Component
{
constructor(props){
super(props);
this.state = {
msg : 'Select Database Operation'
}
}
InsertClick(){
this.setState({
msg: 'Record Inserted'
})
}
render(){
return(
<>
<div className="btn-group">
<button onClick={()=> this.InsertClick()}
className="btn btn-primary">Insert</button>
</div>
<h2 className="text-center">{this.state.msg}</h2>
</>
)
}
}
class MainContent extends React.Component
{
render(){
return (
<div className="container-fluid">
<h3>Event Handling</h3>
<Product />
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);

❖ Event handler

● Event handler is a function pointer.


● Multiple controls can use the same function to handle various functionalities.

Ex:
App.js
class Product extends React.Component
{
DataOperations(e){
switch(e.target.value)
{
case "Insert":
alert("Record Inserted");
break;
case "Update":
alert("Record Updated");
break;
case "Delete":
alert("Record Deleted");
break;
}
}
render(){
return(
<div>
<div className="btn-group">
<button name="btnInsert" value="Insert"
onClick={this.DataOperations} className="btn btn
primary">Insert</button>
<button name="btnUpdate" value="Update"
onClick={this.DataOperations} className="btn btn
success">Update</button>
<button name="btnDelete" value="Delete"
onClick={this.DataOperations} className="btn btn
danger">Delete</button>
</div>
<h2 align="center"></h2>
</div>
)
}
}
class MainContent extends React.Component
{
render(){
return (
<div className="container-fluid">
<h3>Event Handling</h3>
<Product />
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);

❖ Common React Events

● onClick: Used to handle click events on elements like buttons and links
● onChange: Used to handle input changes, such as typed text or selected option
values
● onSubmit: Used to handle form submissions
● onMouseOver: Used when the mouse pointer moves over an element
● onMouseOut: Used when the mouse pointer moves out of an element
● onKeyDown: A keyboard event
● onKeyPress: A keyboard event
● onFocus: A focus event
● onBlur: A focus event

❖ Key Events

● React uses Keyboard events to handle various interactions with regard to key
code, and key actions.
● onKeyDown Indicates the actions to perform
● on key down
● onKeyUp Indicates actions to perform on
● key up.
● onKeyPress Indicates actions to perform
when user finish a key and uses another key.

Properties:-
● keyCode
● charCode
● shiftKey
● ctrlKey
● which
● key [Return the key used]

Ex: Identifying the Key used


App.js
class Register extends React.Component
{
constructor(props){
super(props);
this.state = {
msg: ''
}
this.VerifyPassword = this.VerifyPassword.bind(this);
}
VerifyPassword(e){
if(e.key == "CapsLock"){
this.setState({
msg: 'Caps Lock ON'
})
} else {
this.setState({
msg: ''
})
}
}
render(){
return(
<>
<div>
<lable>Password</lable>
<div>
<input onKeyUp={this.VerifyPassword}
type="password" className="form-control" />
<span>{this.state.msg}</span>
</div>
</div>
</>
)
}
}
class MainContent extends React.Component
{
render(){
return (
<div className="container-fluid">
<h3>Event Handling</h3>
<Register />
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
Ex: Actions on specific key handling
class Register extends React.Component
{
VerifyChar(e){
if(e.key=="y") {
location.href="http://www.amazon.in";
} else {
document.write("Action Canceled..");
}
}
render(){
return(
<>
<input onKeyUp={this.VerifyChar} type="text"
placeholder="Y to Continue and N to Stop" />
</>
)
}
}

❖ Synthetic Event

● React.js manages the cross-browser compatibility by


using “SyntheticEvent”.
● SyntheticEvent is a part of React.js Event Handling.
● It is responsible for making the react event compatible with “cross-browser”.-
● Events can work identically across all browsers.
● The event argument “event” is managed by SyntheticEvent object of React.js
● It is responsible for making the event native for specific browser.

Ex: Get all properties of SyntheticEvent


App.js
class Register extends React.Component
{
RegisterClick(SyntheticEvent){
for(var property in SyntheticEvent)
{
document.write(property + "<br>");
}
}
render(){
return(
<>
<button value="Register"
onClick={this.RegisterClick}>Register</button>
</>
)
}
}
class MainContent extends React.Component
{
render(){
return (
<div className="container-fluid">
<h3>Event Handling</h3>
<Register />
</div>
)
}
}
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);

You might also like