04/09/2024
While working with keyboard events some of the common arguments that are used:
-keyCode: it returns actual ASCII code of key
-charCode:it returns code of char according to UTF
-which : similar to keycode but compatible with different layouts//recommended to use
-shiftkey -
-ctrlKey - they are Boolean values returning true or false
-altKey -
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('')
const [codeError, setCodeError] = useState('d-none')
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')
}
}
}
function VerifyCode(e) {
if (e.which >= 65 && e.which <= 90) {
setCodeError('d-block')
} else {
setCodeError('d-none')
}
// console.log(e.which)
}
return (
Register user
Username
{userError}
Password
{pwdError}
{pwdError}
Verify Code
Warning: CAPS is on
)
}
Element State events:
-onChange: action when value changes
-onBlur: action when element losses focus
-onFocus: action when element got focus
ex:
import { useState } from "react"
export function StateEvent() {
const [msg, setMsg] = useState('')
const [code, setCode] = useState('')
function HandleFocus() {
setMsg('IFSC Code: SBIN0001498,HDFC0000567')
}
function HandleBlur() {
setMsg('')
}
function HandleChange(e) {
setCode(e.target.value.toUpperCase())
}
return (
State Event
Bank IFSC Code
{msg}
)
}
button events:
onClick
onDoubleClick()
onContextMenu : action on right click
onSelectStart:
import { useState } from "react"
export function StateEvent() {
function HandleDblClick() {
window.open('iphone15.png', "Iphone", 'width=300 height=300')
}
return (
Button Event
Double Click on the image to view large
)
}
//how to disable right click
import { useState } from "react"
export function StateEvent() {
function HandleDblClick() {
window.open('iphone15.png', "Iphone", 'width=300 height=300')
}
function HandleContextMenu() {
document.oncontextmenu = function () {
return false
}
}
return (
Button Event
Double Click on the image to view large-right click is disabled
)
}
Handling API:
What is distributed computing?
we have different type of computing archirecture:
-cluster computing
-parallel computing
-grid computing
-distributed computing
-cloud computing
Two different application running on two different machines/devices can share info is called distributed computing.
under distribueted computing we have :
-CORBA
-RMI
-EJB
-Webservices
-Remoting
In this webservices is quite popular ,but has certain limitations
Thus we got a new solution as API
API: Application programming interface
Distributed architecture.
How the communication happens:
-SOAP
-REST
-JSON
SOAP:
-Consumer will make an XML request
Electronics
producer will provide an XML response
TV1000>
-----
-----
Another
Rest
representational state transfer
consumer send a simple query request
http://server.com/shop?category=electronics
u will get response as JSON or XML
JSON: customer send json request and receives json response
https://fakestoreapi.com
it provides REST full services for ERP
Request Route Description
GET /products return array of products [{},{}]
GET /products/1 return specific product by id
GET /products/categories return a string of all categories
GET /products/categories/electronics return all product of specific categories
ex;
import axios from "axios"
import { useEffect, useState } from "react"
export function FakeStore() {
const [category, setCategory] = useState([])
const [products, setProducts] = useState([{ id: 0, title: '', category: '', price: 0, description: '', image: '', rating: { rate: 0, count: 0 } }])
const [cartCount, setCartCount] = useState(0)
const [cartItems, setCartItems] = useState([])
let session = window.sessionStorage.setItem('name', 'abhi')
function LoadCategory() {
axios.get("https://fakestoreapi.com/products/categories")
.then(response => {
response.data.unshift("all")
setCategory(response.data)
})
}
function LoadProducts(url) {
axios.get(url)
.then(response => {
setProducts(response.data)
}, [])
}
function handleCategoryChange(e) {
if (e.target.value === "all") {
LoadProducts("https://fakestoreapi.com/products")
window.sessionStorage.getItem('name')
}
else {
LoadProducts(`https://fakestoreapi.com/products/category/${e.target.value}`)
}
}
function NavbarClick(categoryName) {
if (categoryName === "all") {
LoadProducts("https://fakestoreapi.com/products")
} else {
LoadProducts(`https://fakestoreapi.com/products/category/${categoryName}`)
}
}
function handleProductDetails(product) {
cartItems.push(product)
setCartCount(cartItems.length)
}
useEffect(() => {
LoadCategory()
LoadProducts('https://fakestoreapi.com/products')
}, [])
return (
Fakestore
ElectronicsJwelleryMen's fashionWomen's Fashion
Cart Items
Title
Preview
Price
{
cartItems.map(item =>
{item.title}
{item.price}
)
}
{
products.map(product =>
{product.title}
Price
{product.price}
Rating
{product.rating.rate} {product.rating.count}
)
}
)
}
React Hooks:
Introduced after react 17
Hook is a service
What is service?
-service is a pre defined business logic which allows us to implement and customise using our req.
service contains different components:
provider
consumer
injector
provider will verify whether the required service is present or not
it will locate the service of memory
with the help of injector we will inject the service into the component/app
the app/component which uses the service is called as consumer.
The whole process is called Dependency Injection.
React hooks:
-functions that return pre defined functionality which a component can implement and cutsomise accordingly
useState()
we need to follow certain rules to create custom hooks:
-hook must be a function
-it cannot be void type
-must return something
-you must configure it at higher level component
you cant configure hook in any other function or block
it must be global
hooks are not allowed inside a class component
It must be in camel case.
React hooks:
-only for function components
-service
-singleton pattern
-DI
-provider
-injector
-consumer
-custom hooks
-hook rules
React Built in hooks:
1.useState()
It configures a local state
const[getter,setter]=useState(any data type)
2.useContext() context here refers to context memory/memory
useContext() is not to create context memory but to use the context memory which is already available
how can u use context memory until u create it
In order to create context memory :
createContext(null)
import { createContext, useContext, useState } from "react"
let userContext = createContext(null)
export function Level1Component() {
let context = useContext(userContext)
return (
Level-1 Component-{context}
)
}
export function Level2Component() {
let context = useContext(userContext)
return (
Level-2 Component-{context}
)
}
export function ContextDemo() {
const [userName, setUserName] = useState('Abhi')
function handleNameChange(e) {
setUserName(e.target.value)
}
return (
Context Demo -{userName}
)
}
useReducer():
how to transport data if its not within that context:
application state
session state
It is used to configure application memory
Reducer maintain application state which provide data to all session in application.
problem for application state:
-not a predictable state (not sure about the data or memory might change according to situation based on users)
not debuggable
Reducer provides various components:
-Store
-State
-UI
-reducer
Store is a global location where data is kept
State is responsible for accessing the data from store and provides to UI component
UI is the location where we present data and handle data manipulation
reducer configure the actions and manages the state .It triggers the actions and update the info on the store
configure store with initial store
let initialState={likesCount:0}
function reducer(state,action){
switch(action.type)
{
case: "addLike"
return(likesCount:state.likesCount+1)
case: "addDisLike"
return(likesCount:state.likesCount-1)
}
const[state,dispatch]=useReducer(reducer,initialSate)
ex:
import { useReducer } from "react"
export function ReducerDemo() {
let initialState = { likesCount: 0 }
function reducer(state, action) {
switch (action.type) {
case "addLike":
return ({ likesCount: state.likesCount + 1 })
case "addDislike":
return ({ likesCount: state.likesCount - 1 })
}
}
const [state, dispatch] = useReducer(reducer, initialState)
function handleLikeClick() {
dispatch({ type: 'addLike' })
}
return (
{state.likesCount} likes
)
}
Routing in React:
Web development is all about dealing with some objects and its techniques
objects:
-request
-response
-session
-application
-cookie
techniques:
-databinding
-stylebinding
classbinding
eventbinding
State management
Caching
Routing
Routing is a technique used in web-application to configure user and SEO friendly URLS
u can search URL insode url
old era:
https://www.amazon.in/shop.jsp?category=electronic&product=mobile&model=apple
www.aamazon.in/shop/electronics/mobile/apple
client side routing:
it allows you to design SPA(single page application)
User stays in one page and gets access to everything in the page
routing implicitly uses AJAX.It loads the new content into page without reloading the page.
routing is not a part of react and also not a third party library
It doesn't directly come with react u need to have it as a separate library
currently its version 6
Concept same ,but different ways to use it
React both version:
-react-router-domV5
-react-router-domV6
https://reactrouter.com/en/main -official site
setup routing in ur project sepeartely
Install router DOM library
npm i react-router-dom --save
components in react routing:
Browser router creates a virtual DOM route that maps to actual DOM
In JS we use location to navigate from one page to another
All routes must be configured inside "browserrouter"
Routes is a colletion of route which configures a routing table
each individual route in routing table is defined by route
On request what need to delivered is maintained in routing table
Synatx:
import "./routerdemo.css"
import { BrowserRouter, Route, Routes, Link } from "react-router-dom"
import { Login } from "../login"
export function RouterDemo() {
return (
React Developer
AboutMy ProjectsMy ResumeLogin
UI/UX Developer
HTML|CSS|JS
}>
About Me
I am a Web Developer Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corporis illo vero fugiat a fugit inventore! In nihil illo est, dolorem necessitatibus impedit eligendi explicabo dolorum! Laboriosam rem consectetur itaque nemo.}>
Unable to find anything}>
)
}
React Material UI
-Library provided by react community to build interactive UI for react application.
Its a library with built in components for UI and UX.
MUI core-free
MUI X -licensed
MUI core: component library for react
Provides free functional component for react
open source and cross browser
latest version of MUI is completely rewritten
Now its function based components ,previously its class based components
they have provided @emotion library as new integration to its functional component.
-----------------------------------------------------------------------------------------------------------
Typescript
Issues with JS:
-not a strongly typed language
-not implicitly strictly typed
-not an OOPS language (Supports some oops concept)
-Security issues
-extensibility issues
Strictly typed mode of JS
Implicitly strictly typed
OOPS language
typescript actually uses typescript
let first see compiler architecture:
Core typescript compiler:
-scanner.ts: input (like scanf in c)
-emitter.ts: output(like printf)
-checker.ts: checking the data type
-program.ts: handling program structure
-core.ts: verify keywords
Standalone TS compiler:
-convert typescript to JS(which is understandable by browser)
language service:
-it provides all functions and values for typescripts(built in functions)
server
Shimp:
makes language platform independent apart from cross browser
Managed language service:
code is compiled in a way which is understood by any OS
Setup:
open cmd prompt
-npm install -g typescript
g is for globally
if we want to check the version
tsc -v
create a folder in ur system
D:/typesc
open this folder with VS
open integrated terminal env:
type tsc -init
(if u get error use tsc.cmd -init)
a config.json file will be created
which will contain all the configuration required
ex: which version of JS will the typescript code be converted to
Note: previously we used to have two files
config.json file
tslint file
lint: language analayis tool (you can set rules for the language and issue alert,warnings error)
u need to create a TS file:
index.ts
write:
var x = 10;
console.log("x is ", x)
execute type script file in command line using
node index.ts
u need to convert this into JavaScript
tsc index.ts (if any error comes: use tsc.cmd index.ts)
it will convert typescript to javascript
index.js(this can be linked to any HTML file)
variables in typescript:
same like js
var let const
TS is a strongly typed language so data type specification is required
var name:datatype
let name:datatype
const name:datatype=value
but if u see code in react or angular u will find that they wont specify data type many time:
- TS has a concept called as type inference
var price=number
price="abhi"//invalid
number (signed,usngined,big int etc)
string
null
undefined
Typescript supports union of types:
var uname:string|null
var price: number|string
var price: number | string
price = "abhi";
price = 30
price = true
array:
:arrays are used in computer programming for overhead and complexity
array reduces overhead by storing values in sequential order
array reduces complexity by storing multiple values
TS and JS can handle various types of elements
In addition TS can restrict various array to similar type of elements
size can change dynamically
TS array:
-TS allows array declaration using var and const
if u want array to handle various types of data then define its as any
syntax:
var values:any[]
i want to restrict it:
-var values:string[]
-var values:number[]
array declaration is not enough we need to initialise it to store any values further
var values:any[]=[]
var value:any[]
values=[]
initilaise it using constructor
var values:any[]=new Array();
array manipulation is exactly same as JS
sorting filtering etc
object type:
JS object its dynamic
Data type is determined at the run time based on what we have defined
var product:{name:string,price:number,stock:boolean}={}
var product: { name: string, price: number, stock: boolean } = {
name: "Samsung",
price: 2000,
stock: true
};
operators are exactly same
statements,jump looping conditions all are exactly same
Typescript function
-Some changes here:
In JS function we dont have any data type
IN TS we need to have type specification for both parameter and function
syntax:
function Name(param:type):type|void
{
}
function Details(id: number, name: string): void {
console.log(id)
}
function Addition(a: number, b: number): number {
return a + b
}
Details(2, "A")
In react how to use:
function Login():JSXElement
{
return()
}
OOPS
JS also supports OOPs but few of them
in TS its a proper OOPS language