Event Arguments:
-It comprises of payload which is data about element and event sent to its subscriber
JS event supports
1.Default arguments
2.Custom arguments
Default arguments:
-this: It sends information about the current element
-event: It sends information about the current event
this payload contains details like id,name,value,class src href etc
event payload contains detail like clientX,clientY,ctrlkey,altkey etc
ex:
https://www.google.com
custom arguments:
event can configure custom arguments
-primitive
-non primitive
it also supports spread and rest operators
spread:
var arr1 = [1, 2, 3]
var arr2 = [4, 5, 6]
var arr3 = [...arr1, ...arr2]
console.log(arr3)
rest
function sum(x, y) {
return x + y
}
// console.log(sum(1, 2))
// console.log(sum(1, 2, 3, 4))
function addition(...abhi) {
let sum = 0;
for (let i of abhi) {
sum += i
}
return sum;
}
console.log(addition(1, 2))
console.log(addition(1, 2, 3, 4))
console.log(addition(1, 2, 3, 4, 5, 6))
custom arguments ex:
binding
How do we use arguments in event listener?
-event listener will not support different type of args.It implicitly uses only a refrence of events .Hence only one parameter is allowed in listener which can access both event and element details
ex:
function bodyLoad() {
document.querySelector("button").addEventListener("click", (e) => {
document.write(`X position:${e.clientX} button id:${e.target.id}`)
})
}
There is no chance of custom arguments ,so we will require some other techniques to pass our own data or custom arguments.
What is event propagation.How to prevent it?
Its a mechanism where child event triggers it parent element events.
It is also termed as event bubbling.
ex:
we can prevent propagation of child events by using the event argument method
stopPropagation()
How to disable the generic functionality of elements?
In form button have an inbuilt functionality of submit.But what if we want to write our own functions and we would also like to execute/point only to our function rather than executing their own functionality.
e.preventDefault()
Event is jS belongs to browser window object so react cannot use browser events directly ,so react have synthetic events library which provide events for virtualDOM
Actual DOM Virtual DOM
onclick onClick
onchange onChange
react event handlers have default payload sent to subscriber as event argument
react subscriber function can access and use the event argument
react cant send data using this keyword.it actually uses event to send both element and event details.
react passes the default event argument implicitly
function InsertClick(e){
e.clientX
e.clientY
e.shiftkey
e.target.value
e.target.id
}
how to pass custom arguments
export function EventDemo() {
function InsertClick(msg) {
console.log(msg)
}
return (
Event Demo
)
}
React will not allow to pass custom arguments directly using delegate signature(function pointer signature)
Custom arguments can be passed by using a function return in event handler.
What if we want to send both default and custom arguments:
export function EventDemo() {
function InsertClick(e, ...msg) {
console.log(`X position :${e.clientX}\n Message: ${msg}`)
}
return (
Event Demo
)
}
explicitly we need to send default argument
In our case we are sending here through e
Stop propagation and prevent default is same in react like JS
ex stoppropagation
export function EventDemo() {
function NavClick() {
alert("Navbar is Clicked")
}
function BtnClick(e) {
e.stopPropagation()
alert("Button is Clicked")
}
return (
Event Demo
)
}
ex for prevent default
export function EventDemo() {
function NavClick() {
alert("Navbar is Clicked")
}
function BtnClick(e) {
e.stopPropagation()
alert("Button is Clicked")
}
function handleSubmit(e) {
e.preventDefault()
alert("form submitted")
}
return (
Event Demo
)
}
Now we are going to discuss about synthetic events:
-Mouse events
-keyboard events
-button events
-element state events
-clipboard events
-timer events
-touch events
let us do for mouse events
-onMouseover
-onMouseout
-onMouseup
-onMousedown
etc
let us take example for real time mouse over :
https://www.flipkart.com/apple-iphone-15-blue-128-gb/p/itmbf14ef54f645d
if u see in the above page once u do mouse over it will preview the images
lets recreate the scenario:
have some images in ur public folder of mobile phones
create a jsx file
mouse-demo.jsx and create a json file
json file:
[
{
"img_src": "iphone-2.jpg"
},
{
"img_src": "iphone-3.jpg"
},
{
"img_src": "iphone-4.jpg"
},
{
"img_src": "iphone-5.jpg"
}
]
and write the code in jsx file
import { useEffect, useState } from "react"
import axios from "axios"
import './mouse-demo.css'
export function MouseDemo() {
const [images, setImages] = useState([{ img_src: '' }])
const [preview, setPreview] = useState('')
function LoadImages() {
axios.get("mobiles.json")
.then(response => {
setImages(response.data)
})
}
useEffect(() => {
LoadImages()
}, [])
function DisplayImage(e) {
setPreview(e.target.src)
}
return (
{
images.map(image =>
)
}
)
}
for providing border hover effect we can use css file
create mouse-demo.css file
.col-2 img:hover {
border: 2px solid blue
}
We will learn stylebinding in react
-Stylebinding is a technique where the styles are configured dynamically for an element.
inJS
-
Welcome
document.querySelector("h1").style.textAlign="center"
we have already read in previous classs that will applying CSS dynamically it will change to camelCasing.
text-align=>textAlign
background-color=>backgroundColor
color=color
In react how are we gonna bind the styles
jsx elements can bind the style dynamically by using binding expression
//in html its ok but in react its invalid
Abhi Shopping Cart
ex of style bnding with events:
import { useState } from "react"
export function StyleBinding() {
const [textColor, setTextColor] = useState({ color: "black" })
function ChangeColor(ourcolor) {
setTextColor({ color: ourcolor })
}
function ResetColor() {
setTextColor({ color: 'black' })
}
return (
Style Binding
ChangeColor('red')} onMouseOut={ResetColor}>
ChangeColor('blue')} onMouseOut={ResetColor}>
ChangeColor('green')} onMouseOut={ResetColor}>
Demo Text
)
}
synthetic events another example combined with stylebinding:
import { useState } from "react"
export function StyleBinding() {
const [styeObj, setStyleObj] = useState({ position: '', top: '', left: '' })
function GetPosition(e) {
setStyleObj({ position: 'fixed', top: e.clientY + "px", left: e.clientX + "px" })
}
return (
move mouse pointer
)
}
React Class Binding:
-class binding is a technique used to configure CSS classes to element dynamically
jsx cant use class attribute to bind css class
jsx requires className property to bind a class
className is defined in a string format
syntax:
{}
ex:
create a classbinding.jsx and enter below code:
import { useState } from "react"
export function StyleBinding() {
const [theme, setTheme] = useState('')
const [btnTheme, setBtnTheme] = useState('btn btn-dark w-100')
function SwitchTheme(e) {
if (e.target.checked) {
setTheme("border border-1 p-4 bg-dark text-white")
setBtnTheme('btn btn-light w-100')
}
else {
setTheme("border border-1 p-4")
setBtnTheme('btn btn-dark w-100')
}
}
return (
)
}
@keyframes [name]{
from{
styles
}
}
to{
styles
}
the name defines the name of the animation
style -cSS style properties
animation :
import { useState } from 'react'
import './animation-demo.css'
export function AnimationDemo() {
const [aniStyle, setAniStyle] = useState('')
function SpinClick() {
setAniStyle('image-spin')
}
function ZoomClick() {
setAniStyle('image-zoom')
}
return (
)
}
in css we can add the below code:
@keyframes Spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@keyframes Zoom {
from {
transform: scale(0.5);
}
to {
transform: scale(2);
}
}
.image-spin {
animation-name: Spin;
animation-duration: 5s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
.image-zoom {
animation-name: Zoom;
animation-duration: 5s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
now we will disucss about keyboard events:
-onKeyUp
-onKeyDown
-onKeyPress
keyup and keydown are the events used with elements when u are verifying input chars
keypress is used with elements when u are verifying the ASCII code of input chars
keypress fires up when u finish current key and start typing/keying another char
in JS
ex:
Document
Username:
ex in react:
import { useEffect, useState } from "react"
import axios from "axios"
export function KeyDemo() {
const [users, setUsers] = useState([{ UserId: '' }])
const [userError, setUserError] = useState('')
const [userClass, setUserClass] = useState('')
useEffect(() => {
axios.get("users.json")
.then(response => {
setUsers(response.data)
})
}, [])
function VerifyUser(e) {
var userId = e.target.value
for (var user of users) {
if (user.UserId == userId) {
setUserError('User Id already taken -try another one')
setUserClass('text-danger')
break;
} else {
setUserError('User Id is availaible')
setUserClass('text-success')
}
}
}
return (
Register user
Username
{userError}
Password
)
}
if we want to have pwd verification based on reg expression and combine some styling to it
import { useEffect, useState } from "react"
import axios from "axios"
export function KeyDemo() {
const [users, setUsers] = useState([{ UserId: '' }])
const [userError, setUserError] = useState('')
const [pwdError, setPwdError] = useState('')
const [userClass, setUserClass] = useState('')
useEffect(() => {
axios.get("users.json")
.then(response => {
setUsers(response.data)
})
}, [])
function VerifyUser(e) {
var userId = e.target.value
for (var user of users) {
if (user.UserId == userId) {
setUserError('User Id already taken -try another one')
setUserClass('text-danger')
break;
} else {
setUserError('User Id is availaible')
setUserClass('text-success')
}
}
}
function VerifyPassword(e) {
if (e.target.value.match(/(?=.*[A-Z])\w{4,15}/)) {
setPwdError("Strong Password")
setUserClass('text-success')
} else {
if (e.target.value.length < 4) {
setPwdError("Poor Password")
setUserClass('text-danger')
} else {
setPwdError("Weak Password")
setUserClass('text-warning')
}
}
}
return (
Register user
Username
{userError}
Password
{pwdError}
)
}
ex:
import { useEffect, useState } from "react"
import axios from "axios"
export function KeyDemo() {
const [users, setUsers] = useState([{ UserId: '' }])
const [userError, setUserError] = useState('')
const [pwdError, setPwdError] = useState('')
const [userClass, setUserClass] = useState('')
const [pwdStrength, setPwdStrength] = useState({ width: '' })
const [bgClass, setBgClass] = useState('')
useEffect(() => {
axios.get("users.json")
.then(response => {
setUsers(response.data)
})
}, [])
function VerifyUser(e) {
var userId = e.target.value
for (var user of users) {
if (user.UserId == userId) {
setUserError('User Id already taken -try another one')
setUserClass('text-danger')
break;
} else {
setUserError('User Id is availaible')
setUserClass('text-success')
}
}
}
function VerifyPassword(e) {
if (e.target.value.match(/(?=.*[A-Z])\w{4,15}/)) {
setPwdError("Strong Password")
setUserClass('text-success')
setPwdStrength({ width: '100%' })
setBgClass('bg-success')
} else {
if (e.target.value.length < 4) {
setPwdError("Poor Password")
setUserClass('text-danger')
setPwdStrength({ width: '35%' })
setBgClass('bg-danger')
} else {
setPwdError("Weak Password")
setUserClass('text-warning')
setPwdStrength({ width: '55%' })
setBgClass('bg-warning')
}
}
}
return (