React Data Binding
Accessing data from memory source/reference and present it to the UI.it should also allow user to modify it and save back in the memory.
Data binding:
-It is a technique of web-application
-It allows user to access data from memory sources and bind it to UI elements
-It also allows to identify the change in data form UI and update back to memory sources i.e vice versa
but in react data binding is a one way traffic.
In JS we require lot of DOM methods to achieve data binding.
In react we dont use variables to achieve data binding but rather we use state techniques
States available in web development:
-local storage
-cookies
-session storage
-query string
why we need state?
since http is a stateless protocol as each request is executed independently ,without any knowledge of the requests which was executed before.
http cant remember informations between requests
to overcome this problem web application uses different state management techniques.
ex: local storage
create a html file and paste the below code:
Document
create another html file as demo.html and paste the below code:
Document
Welcome
in the above example we are able to transfer data between two pages using local storage state management techniques.
session storage is similar to local storage :
Document
in demo.html just change below lines:
function bodyLoad() {
document.querySelector("p").innerHTML = sessionStorage.getItem("uname")
}
but the difference lies here is that data in local storage doesn't expire while data in session storage is
cleared out whenever the page session will end
React can use all state management techniques ,but if we do so the whole purpose of react will be defeated.
bcoz these state management techniques are on client side which is actual DOM but react uses virtual DOM.
Thus react provides u with useState() which is a hook function to maintain state
various hooks available for us:
-useState()
-useContext()
-useReducer()
-useMemo()
-useCallback()
React also provide third party state management techniques like Redux
Redux: A JS library for predictable and maintainable global state management
syntax: const[getter,setter]=useState(value)
why we use const but not let or var?
-bcoz let or doesn't mandate us for initialising,while for const its manadatory to be initialised.
Note: State always must be initilaised.
example:
import { useState } from "react"
import "./login.css"
export function Login() {
const [title, setTitle] = useState('Customer Login')
const [uname, setUname] = useState("Abhijeet")
return (
)
}
suppose user wants to set the value of the state after initialisation
export function DataBinding() {
const [name, setName] = useState("");
setName("Abhijeet")
return (
Data Binding
Name: {name}
)
but he will encounter an issue called as :
"Too many re-renders. React limits the number of renders to prevent an infinite loop."
how to stop this error
if we go back to JS in the below example we have defined the event when actually we need the function/initialisation to happen such as onLoad
Document
thus in react we need to define the event when u want the initialisation
this happens during your component mount phase.
Component mount phase
->Mounting is the initial phase in which the instance of the component will be created and inserted into the DOM/virtualDOM.
mount we can resemble to onload.
component mount phase is configured by using useEffect() hook function
syntax for useEffect:
-useEffect(()=>{
},[dependencies])
note: please import:
import { useEffect} from "react"
why dependencies is an array?
-bcoz we can have multiple events to trigger it
import { useEffect, useState } from "react"
export function DataBinding() {
const [name, setName] = useState("");
const [uname, setUname] = useState("")
useEffect(() => {
setName("test");
setUname("abhi.gmail")
}, [])
return (
Price: {price}
parsing is same
parse int
parse float
isNaN() to test if value is not a number
converting to locale string is also same
useEffect(() => {
setPrice(6700000.876);
}, [])
return (
)
Boolean
React Boolean is same as JS
handles true or false
React JSX cannot display Boolean values directly
but we can use some expression and show it
ex:
const [price, setPrice] = useState("");
useEffect(() => {
setPrice(true);
}, [])
return (
Data Binding
Price: {(price) ? "true" : false}
)
JSX doesn't allow statements or loops
Strings:
can be configured by using
-double quote ""
-single quote ''
-backtick ``
allows for expression (data binding) in JS
${}
all string manipulation and formatting are same in js and react
ex:
bold()
italics()
fontcolor()
toLowerCase()
toUpperCase()
charAt()
startsWith()
trim()
match()
onst [price, setPrice] = useState("");
const [title] = useState('Data Binding')
useEffect(() => {
setPrice('bg-dark');
}, [])
return (
{title.toLowerCase()}
undefined and null
undefined keyword is used to verify value at compile time
null keyword is used to verify the values at run time:
ex:
const [name, setName] = useState("");
useEffect(() => {
setName(prompt('enter the name'))
}, [])
return (
{
(name == null) ? "please provide the name" : name
}
date() in JS
In react also we can use/implement all date related functions
react can use all date methods of js
getHours()
getMinutes()
getSeconds()
getDate()
getMonth()
getDay()
etc
but react works with virtual DOM ,while date related functions works with actual DOM ,hence in multiple places u will get error
soln: We will use some data adapter for virtual DOM(third party tool)
-dayjs
-moment etc
go o https://www.npmjs.com/
install moment
npm i moment -save
import moment from 'moment'
ex:
const [mfd, setMfd] = useState("");
useEffect(() => {
setMfd(Date())
}, [])
return (
Date:{moment(mfd).format('dddd:mm:yy')}
Regular expression:
A regulat expression comprises of meta characters and quantifiers
expression enclosed in "//"
const [regExp] = useState(/(?=.*[A-Z])\w{4,15}/);
useEffect(() => {
}, [])
return (
{('Abhi1234'.match(regExp)) ? "name is entered in correct format" : "please enter name in correct format"}
)
Array:
-All array concept will be same as in JS
-all array methods will be same
but how we present array is different in react
ex:
first in JS
Document
then in react:
import { useEffect, useState } from "react"
export function DataBinding() {
const [categories] = useState(["Mens", "Womens", "Kids"]);
useEffect(() => {
}, [])
return (
{
categories.map(category =>
{category}
)
}
)
}
Object:
Java script objects and its manipulation is same in react.
Object keeps all data and its logic together
Its a key value collection.
example:
import { useEffect, useState } from "react"
export function DataBinding() {
const [product] = useState({ Name: 'Bosch', Price: 45000, cities: ["Chennai", "Hyderabad"], Rating: { Rate: 4.2, Count: 150 } });
useEffect(() => {
}, [])
return (
)
}
Task: Recreated the flipkart page wich has iPhone 15 mobile display for purchase:
for that we need some data which cant be hardcoded so we will be using a jSON file to store the data and retrieved it
create a json file called product.json
{
"title": "Apple iPhone 15 (Black, 128 GB)",
"price": 75999,
"rating": {
"rate": 4.6,
"ratings": 4800,
"reviews": 12000
},
"offers": [
"Bank Offer5% Unlimited Cashback on Flipkart Axis Bank Credit CardT&C",
"Special PriceGet extra ₹11901 off (price inclusive of cashback/coupon)T&C",
"Partner OfferMake a purchase and enjoy a surprise cashback/ coupon that you can redeem later!Know More",
"Extra 10% Off On Combo Mobile & Case - AlphaT&C"
],
"image": "iphone15.png"
}
now create a skeleton and capture all the data accodinly in the componenet
import { useEffect, useState } from "react"
export function DataBinding() {
const [product, setProduct] = useState({ title: "", price: 0, rating: { rate: 0, ratings: 0, reviews: 0 }, offers: [], image: "" })
function LoadData() {
var http = new XMLHttpRequest();
http.open("get", "product.json", true)
http.send()
http.onreadystatechange = function () {
if (http.readyState == 4) {
setProduct(JSON.parse(http.responseText))
}
}
}
useEffect(() => {
LoadData();
}, [])
return (
)
}
in the above example we have used XMLhttprequest .What is that?
In JS we have some ajax technique to access data from files
-XMLHttpRequest
-fetch()
-XMLHttpRequest
1)Implicitly synchronous
2)poor in error handling
but its a native method and browser can understand it.
Note: All other Techniques used finally calls XMLHttpRequest only
its defined by javascript window.
it can create async request(explicitly) and handle interaction with remote file and URL
step1:
-create a new object for XMLHttpRequest
var http = new XMLHttpRequest();
step2:
-Configure the method and which file is to be fetched
http.open("method", "fileurl", "true/false")
methods: get post put patch delete
Step3:
send request to file or URL through browser
http.send
step 4:
check the status and configure the function accordingly
http.onreadystatechange = function () {
if (http.readyState == 4) {
setProduct(JSON.parse(http.responseText))
}
}
ready state :holds the status of the XML http request.
limitations:
-it not completely or implicitly async
-it returns response in various formats like XML,text html,problem here is that we need to have different parsing techniques.
-since there are multiple formats of data ,even firewall can take it as a threat and can block the data
-poor error handling.
to overcome this in modern JS we have something called as fetch
fetch in backend actually uses XMLHttpRequest
it is aync by default
its a JS promise
fetch("URL/File").then ().catch().finally()
then: executes on success and returns a response object that contains the response data
catch: executes on error and returns an error object that contains error details
finally: always executes
ex:
fetch("product.json")
.then(response => {
return response.json()
})
.then(product => {
setProduct(product)
})
issues with fetch:
-Data is returned in binary format so we need to explicitly convert it.
-binary conversions may be blocked by firewall.
-It catches error but unable to exactly tell where or what the error is.
JQuery-write less do more
It provides various DOM interaction methods and ajax methods
it is good in tracking errors because it has life cycle events.
it doesn't require parsing techniques.
$.ajax()
$.getJson()
ajaxStart()
ajaxStop
ajaxSuccess
ajaxerror
etc
so we need to install jquery first
npm install jquery --save
import $ from "jquery" either in central file ie index.js or u can import in specific components
$ => js query core which comprises of all jquery methods
jquery ajax call is configured by using ajax methods:
$.ajax({
method:get|post|put|patch|delete,
url:"",
success:function(){} // returns response object
error: function(){} //returns error object
})
ex:
$.ajax({
method: "get",
url: "product.json",
success: (response) => {
setProduct(response)
},
error: (abhi) => {
alert(abhi)
}
})
limitations:
-Since jquery uses actual DOM its not viable for react as react interacts with virtualDOM.
-CORS [cross origin source sharing]
-Request forgery
-XSS [cross site scripting attacks]
solution:
React will use 3rd party Ajax libraries
-Telerik
-Axios
-Whatwgfetch
axios is free third party library used for react AJAX
JS library used to communicate with remote url/files ,api etc
Configure and handle ajax by using axios
It provides virtual DOM interaction.
It can handle CORS
handle cross site scripting
prevents request forgery
good in error handling
go to https://www.npmjs.com/
search axios
npm install axios --save
import axios from "axios"
axios.get
axios.post
axios.put
etc
syntax:
promise based
axios.get("url").then(()=>{}).catch(()=>{}).finally(()=>{})
then: return response object with various response details
status[code]: 200,404
statustext : OK ,not found
headers get post
data: data returned
React support one way binding implicitly.
but react claims this as a gud feature as it doesnt want users to update the memory/data accidently.
To achieve two way data binding we need to define certain events :
onchange() //js
but in js u have other events :
onkeyup
onkeydown
onkeypress
onblur
ex:
import { useState } from "react"
export function OneWay() {
const [userName, setUserName] = useState('Abhi')
function NameChange(event) {
setUserName(event.target.value)
}
return (
One way Binding
)
}
React event Binding:
What is event?
-Event is a message sent by sender to its subscriber in order to notify the change.
It follows a delegate mechanism which is a function pointer mechanism
now there can be scenario where the element is created dynamically ,then how are we gonna write event handler
as event handler needs markup/element to be present
in those scenario we will use event listener
ex: in js
Document
What are event arguments?
-It comprises of payload which is data about element and events sent to its subscriber.
JS event argument supports:
1.Default argument
2.Custom argument
Default arguments:
-this: It sends information about current element
-event: It sends information about current event
ex:
Document
Custom arguments:
1.primitive
2.non primitive
it also supports spread operator and rest
spread
var arr1 = [10, 20, 30]
var arr2 = [35, 45, 65]
var arr3 = [...arr1, ...arr2]
console.log(arr3)
rest :
function addition(...myargs) {
let sum = 0;
console.log(myargs)
for (let i of myargs) {
sum += i;
}
return sum
}
console.log(addition(2, 3))
console.log(addition(2, 3, 4))
console.log(addition(2, 3, 4, 5))
custom artguments ex:
Document
How do we use arguments in event listener?
Document