Intro to React 18 and Setup: generally till date we have done manual work to create our project now we will take help of tools that will create project for us. We need help of bundlers to create react application -webpack -parcel -vite A bundler is a tool that takes all our code(JS.HTML SASS stc) including dependencies along with images ,videos CSS etc and combines them into a single/few files which is served to browser using client server request. NodeJS has inbuilt support for webpack bundler. Set up react 18 choose a folder from cmd prompt (ex: D:) 1) npx create-react-app react-batchnew you will get a folder structure -node_modules: library files installed for our project( ex React,React DOM,babel etc) -public : static files ( HTML,images,videos etc) -src : dynamic files(ex:JS,JSX,CSS etc) -Git Ignore: It configures the repository to ignore while publishing on git -package-lock.json: migration of project -package.json : project metadata -Readme.md :docs for developers we use npm start to start our server what is this npm start? -Its a batch program to compile and run react applications batch program -A batch program consist of series of commands defined under specified name so that u can execute the commands in sequential order by running the command name where to add batch commands? -package.json file ex: "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "abhi": "npm i bootstrap bootstrap-icons" u can execute by typing: npm run abhi now we will create our own component: -first create a folder in src src/components we will design a login form src/components/login.jsx src/components/login.css (not mandatory) src/components/login.test.js (not mandatory) go to login.jsx and enter the code as: export function Login() { return (

Login

Username
Password
) } now go to css file: .container { display: flex; justify-content: center; align-items: center; height: 100vh; } .frm-login { border: 1px solid gray; padding: 10px; border-radius: 10px; } now we need to call the component in index.js import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { Login } from './components/login'; import "../node_modules/bootstrap-icons/font/bootstrap-icons.css" import "../node_modules/bootstrap/dist/css/bootstrap.css" import bootstrap from "bootstrap" const root = ReactDOM.createRoot(document.getElementById('root')); root.render( < Login /> ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals(); Data binding: -Accessing data from memory source/refrence and presenting to UI,allow user to modify it and save back to memory. Its a technique of web-application It allows to access data from memory source and bind it to UI elements It also allows to identify the change in data from UI and update back to memory source ie vice versa but in react data binding its a one way traffic. React manages one way binding by using expression defined in embedded block: {} ${} //in JavaScript `` JS has state management techniques: -local storage -cookies -session storage -query why we need state? Because HTTP is a stateless protocol as each request is executed independently without any knowledge of the request that were executed before it i.e once the transaction ends the connection between the browser and server is gone. ex: in demo.html Document in welcome.html Document

Welcome

React can use all client state management techniques but the whole purpose of react will be defeated? Why because all the client side management technique are with actual DOM but react claims to work with virtual DOM hence react provide a local state for components so that they can manage data in virtual DOM useState is a hook (function) various hooks we have is: -useState() -useContext() -useReducer() -useMemo() -useCallback() etc syntax: const[getter,setter]=useState(value) Can we use let and var to declare state in react? -yes but not recommended. why we use const ,why not var or let? bcoz initialisation is mandatory ,when u are creating the component at that itself initialsiation has to be done. ex: import { useState } from "react" export function DataBinding() { const [name, setName] = useState('') setName("Abhijeet") return (

Data Binding

) } but in the above example we will get error as too many re-render since we have not defined when the value is to be set ,like ur JS we have bodyload ,similarly here its called component mount phase. hook function useEffect() // component mount phase is configured by using useEffect() hook useEffect can run on every render of the component [when a state variable changes] and can run every time a specific value changes ie mentioned in dependence array use effect accepts two arguments.the second argument is optional useEffect(function{ },[dependencies]) use arrow function useEffect(()=>{ },[dependencies]) ex: import { useEffect, useState } from "react" export function DataBinding() { const [name, setName] = useState('') useEffect(() => { setName("Abhijeet") }, []) return (

Data Binding

Name:{name}
) } Handle various data types: -Number: Its same as in JS ex: import { useEffect, useState } from "react" export function DataBinding() { const [price, setPrice] = useState('') useEffect(() => { setPrice(67000.65) }, []) return (

Data Binding

Price:{price.toLocaleString('en-in', { style: 'currency', currency: 'INR' })}
) } u can use all math functions also Math.pi Math.sqrt etc JS Boolean is same as react handle true or false React JSX cannot display a Boolean values.It can use a Boolean value but cant show the value import { useEffect, useState } from "react" export function DataBinding() { const [price, setPrice] = useState('') useEffect(() => { setPrice(true) }, []) return (

Data Binding

Price:{(price) ? "true" : "false"}
) } JSX doesn't allow to use loop ,if statements etc error import { useEffect, useState } from "react" export function DataBinding() { const [price, setPrice] = useState('') useEffect(() => { setPrice(true) }, []) return (

Data Binding

Price:{if(price==true) { }}
) } expression is required String is confgured using "",'', ``(data binding : ${}) import { useEffect, useState } from "react" export function DataBinding() { const [price, setPrice] = useState('') useEffect(() => { setPrice('bg-dark') }, []) return (

Data Binding

) } string in js is same as react all string manipulation and formatting techniques are same as JS -bold() italics() fontColor() toUpperCase() toLowerCase() charAt() endsWith() etc import { useEffect, useState } from "react" export function DataBinding() { const [price, setPrice] = useState('') const [title, setTitle] = useState('') useEffect(() => { setPrice('bg-dark') setTitle('abhijeet') }, []) return (

{title.toUpperCase()}

) } Regular expression is also same in JS Date also we can use same as JS All array concept is same in JS All array methods is same But how we present array is different in react Object: import { useEffect, useState } from "react" export function DataBinding() { const [product] = useState({ Name: "Bosch", Price: 45000, Cities: ["Chennai", "Hyd"], Rating: { Rate: 4.2, Count: 150 } }) useEffect(() => { }, []) return (

Product Details

Name
{product.Name}
Price
{product.Price.toLocaleString('en-in', { style: "currency", currency: 'INR' })}
Cities
    { product.Cities.map(city =>
  1. {city}
  2. ) }
Rating
{product.Rating.Rate} [{product.Rating.Count}]
) } ex: design an iPhone 15 flipkart page: create product.json file (in public folder) : { "title": "Apple iPhone 15 (Black, 128 GB)", "Price": 57749, "rating": { "rate": 4.6, "ratings": 23000, "reviews": 12000 }, "offers": [ "Bank Offer5% Unlimited Cashback on Flipkart Axis Bank Credit CardT&C", "Special PriceGet extra ₹12151 off (price inclusive of cashback/coupon)T&C", "Extra 10% off on Combo with Mobile - Google,Nothing,AppleT&C", "Extra 15% off on Combo with Mobile - AppleT&C" ], "image": "iphone15.png" } create a state in component const [product] = useState({ title: "", price: 0, rating: { rate: 0, ratings: 0, reviews: 0 }, offers: [], image: "" }) how to read json file and present it to UI? we will be using JS AJAX method: JS technique for AJAX request: 1.XMLHttPRequest 2.fetch() XMLHttPRequest: -implicitly synchronous -manually we need to make it asynchronous -poor in error handling -its a native browser method (browser understand him) Note: all other techniques uses XMLHttprequest in backend import { useEffect, useState } from "react" import "../node_modules/bootstrap-icons/font/bootstrap-icons.css" import "../node_modules/bootstrap/dist/css/bootstrap.css" import bootstrap from "bootstrap" export function Data() { 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 (
{product.title}
{product.rating.rate} {product.rating.ratings} Ratings & {product.rating.reviews} Reviews
{product.price.toLocaleString('en-in', { style: "currency", currency: "INR" })}

Available offers

    { product.offers.map(offer =>
  • {offer}
  • ) }
) } problems : its not implicitly async,u have to explicitly make it. : it returns response in various formats [XML,html,text]=>problem is we need some parsing technique to handle it :not good in error handling no predefined library in JS ,we need to handle it explicitly :since data is in various formats,browser may block it also. :security issue: if any data comes for conversion it will first check whether its ok to covert data and it might block it. fetch() JS fetch uses promise -it is async by default -it provides a better error handling technique as compared to XMLHttprequest 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 return an error object that contain error details. finally: always execute. function LoadData() { fetch("product.json") .then(response => { return response.json() }) .then(data => { setProduct(data) }) } issue with fetch :Data is returned in binary format so we need to convert it :Binary conversion also sometime is blocked by firewall :it uses catch for error handling ,but still it cant catch the exact traces of error. Jquery Ajax: -it introduces approach of write less do more -it provides various DOM interaction methods and AJAX methods it is good in error tracking it doesn't require parsing methods $.ajax() $.getJson() ajax.start() ajax.stop() ajaxSuccess() ajaxError()