React js
React js
React Js FullNotes
these notes consists of some JavaScript topics also…
Godishela Vineeth
AMEERPET TECHNOLOGIES
REACT JS
ReactDay-1
Introduction
React, also known as React.js or ReactJS,
React is a robust and widely-used JavaScript library for developing streamlined, interactive Single Page
Applications (SPAs).
He initiated the development of React while working at Facebook, and the project was open-
sourced by Facebook in May 2013.
History Of ReactJs:
Features of ReactJs:
1
REACT JS
Virtual DOM: React introduces the concept of a Virtual DOM, which is a lightweight copy of the
actual DOM. When changes occur in your application, React updates the Virtual DOM first and
then efficiently updates the actual DOM, minimizing the number of real DOM manipulations. This
leads to better performance and faster rendering.
Reactive Updates: React's one-way data flow and component lifecycle methods make it easy to
manage the state of your application and trigger updates in response to user interactions or data
changes. This predictability simplifies debugging and ensures that your UI remains in sync with
your data.
Cross-Platform Development: React can be used to build not only web applications but also
mobile applications using React Native. This means you can use the same components and
codebase to develop for multiple platforms, saving time and effort.
Community and Ecosystem: React has a large and active community, resulting in a vast
ecosystem of libraries, tools, and resources. This ecosystem makes it easier to find solutions,
learn, and integrate React with other technologies.
Declarative Syntax: React uses a declarative syntax, which means you describe what the UI
should look like based on the current state. This makes the code more understandable and
maintainable compared to manually manipulating the DOM imperatively.
Server-Side Rendering: React supports server-side rendering (SSR), which can improve the initial
loading performance of web applications and enhance search engine optimization (SEO).
Strong Industry Adoption: React is widely adopted by many companies and is used in numerous
production applications, making it a valuable skill for developers in the job market.
2) install node
node –version (if it shows any version then node is installed successfully)
npm –version (if its shows any version then npm is installed successfully)
2
REACT JS
5)Right click on it, it will show “open with code” just click on it you will be redirected to vs code
6)Now in above picture you can see( …) dots at top left, beside Go, just click on three dots
8)inside new terminal write the following command to create react app
Use all lowercase letters for the project name, like "react-batch-two."
Avoid special characters and spaces; use hyphens or underscores to separate words if needed,
such as "react-batch-two" or "react_batch_two."
Choose a descriptive and meaningful name that reflects your app's purpose.
Keep the name concise and clear, avoiding overly long or complex names.
command
3
REACT JS
in above command
npx-The term "npx" stands for "Node Package Runner." It's a package runner tool that comes with npm (Node
Package Manager) and is used to execute binaries from packages that are not globally installed on your system. This
makes it convenient for running packages from the npm registry without needing to install them globally or manage
their versions. You can use npx to run various Node.js and JavaScript-related commands and tools.
The "x" in "npx" doesn't have a specific meaning, and it's not an acronym. It's simply a convention in the naming of
commands and tools. In this context, "npx" is used to run packages, so you can think of the "x" as representing
"execute" or "execute package."
4
REACT JS
3)npm install -g create-react-app [(after using this command) then click enter it will create a react-app
wait for loading or creation
5
REACT JS
Node Modules: This is a directory where your project's dependencies are installed. You typically don't need to
manage the files in this directory manually.
Public: The "public" folder in a React project is used to store static assets and the main HTML file that serves as the
entry point for your application.
index.html: This is the main HTML file that serves as the entry point to your React application. It contains the HTML
structure for your web page
manifest.json: This simple manifest.json file includes the name of the web application as "My React App" and an
empty array of icons.
src
The "src" directory in a typical React.js project is where most of your application code resides. It contains various
JavaScript files, React components, styles, and other assets that make up your web application.
6
REACT JS
index.js: The JavaScript entry point for your React application. This file is responsible for
rendering your main React component and attaching it to the HTML element defined in your
"public/index.html" file.
App.js: The main React component of your application. This is w here your application's UI and
logic are defined. You may also have other components in this directory or in subdirectories.
package.json is a fundamental file in a Node.js project, including React applications. It contains metadata about
the project, a list of its dependencies, and scripts for managing various aspects of the project.
ReadMe.md: A "README" is a documentation file that provides information about your project, its purpose, how
to set it up, and how to use it. It serves as a guide for developers, collaborators, and users.
ReactDay -2
Difference between npm and npx:
npm is the default package manager for Node.js and is used for installing, managing, and
publishing packages (libraries and modules) in the Node.js ecosystem.
You use npm to install packages globally (system-wide) or locally (project-specific) and
manage dependencies for your Node.js projects.
Common npm commands include npm install, npm update, npm uninstall, and npm init,
among others.
npx is a package runner tool that comes with npm and is used for executing packages (or binaries)
without having to install them globally or locally.
npx is particularly useful when you want to run a one-time command from a package that you don't
want to install as a global or local dependency. It allows you to run commands from packages
temporarily.
7
REACT JS
summary, if you want to work with packages, manage dependencies, or publish your own packages, you
use npm. On the other hand, if you want to run a specific command from a package without installing it,
you use npx.
Next follow following steps: 1) first delete all the comments in index.html after reading it .
Here we can see a div with id='root' just observe it then you can see like the following
3) then delete app.js and make the folder structure like the following delete all the files which are not mentioned in
the following image
8
REACT JS
9
REACT JS
Method1:- We are using pure javascript or dom manipulation and displaying the message on
Browser
In the "Old way of React-js," you manually create and manipulate HTML elements using JavaScript, without JSX or
the convenience of React components
10
REACT JS
Instead of using React components and JSX, you create and manipulate HTML elements directly using pure
JavaScript.
While the old way of creating React applications is less common today due to the advantages of using JSX and
ReactDOM, it's essential to understand this approach to appreciate how React has evolved and to troubleshoot
legacy codebases or scenarios where modern tools may not be available or appropriate.
1. React :React is a JavaScript library for building user interfaces. In our code, we 're using React to create a
UI component using JSX syntax.
JSX allows you to write HTML-like code within your JavaScript, making it easier to define the structure
and appearance of your UI elements.
It provides the tools for rendering React components into the actual HTML DOM.
use ReactDOM to render the React element created with JSX. ReactDOM has render method
1)The first parameter is the React element you want to render(what to show)
2)The second parameter is the location where you want to render this element(where to show)
3) The third parameter is an optional callback function that can be executed after the
rendering is complete.
So, in our example, we are using React to create a UI element and ReactDOM to render it in a specific location in
your HTML document, making it visible in your web application.
var React = require('react'); this react module is used to use the JSX syntax
11
REACT JS
var ReactDOM = require('react-dom'); this react-dom helps to render the data ,in react-dom there is a method called
render()
// This is the callback function that will be executed after rendering is complete.
console.log('Rendering is complete.');
document.getElementByID('root') by writing this we are displaying the html tag in index.html(where to show)
Babel:
Babel is a JavaScript transpiler, meaning it converts a newer version of ECMAScript, such as ES9, to a standard version
(ES5)(why because the new version of code is not undestandable by browser).
// Render an "h1" element with the text "HELLO HEROS" into the HTML element with the ID 'root'
ReactDOM.render(
);
---------------------------------------------------------------------------------------------------------
When using the ReactDOM.render method in React, you can only pass a single JSX element as the first argument.
If you want to render multiple elements, you need to wrap them in a single parent element. There are a few ways
to do this:
ReactDOM.render(
<div>
<h1>HELLO HEROS</h1>
<p>Hello heroes</p>
</div>,
document.getElementById('root')
);
12
REACT JS
In this approach, you wrap the multiple JSX elements within a single <div> element.
This parent <div> doesn't affect the styling or layout and is often used to group related elements.
ReactDOM.render(
<>
<h1>HELLO HEROS</h1>
<p>Hello heroes</p>
</>,
document.getElementById('root')
);
Alternatively, you can use a fragment, which is a lightweight way to group elements without adding an extra HTML
tag to the DOM.
Fragments are especially useful when you don't want to introduce unnecessary elements into the layout.
3. Wrapping in an Array:
ReactDOM.render(
[
<h1>HELLO Ameerpet Technologies</h1>,
<p>Welcome to React World</p>
],
document.getElementById('root')
);
You can also wrap the elements in an array. However, when using an array, ensure that each JSX element is separated
by a comma, just like in a regular JavaScript array.
These approaches allow you to render multiple JSX elements under a single parent element, ensuring that
ReactDOM.render receives a single root element to work with. Choose the one that best fits your needs and coding
style.
ReactDay-3
JSX Expression: { }
In JavaScript code, you can include HTML (or JSX) within JavaScript using JSX syntax.
If you want to embed JavaScript within this HTML/JSX, you can do so using JSX expressions denoted by curly braces
{}.
13
REACT JS
This allows you to seamlessly combine JavaScript and HTML/JSX to create dynamic content within your
application.
in this you can only use operations (ex: a+b,1*2.. here it directly returns result) not statements (if-else conditions
why because it have to check condition and then it returns so it won’t work)
JavaScript
JSX(HTML)
{JavaScript}
Example 1:
const lname="Technologies";
ReactDOM.render(
<>
<h1>HELLO {fname}</h1>
<p>Hello {lname}</p>
<p>sum ={1+6}</p></>
,document.getElementById('root')
14
REACT JS
const fname="Ameerpet";
const lname="Technologies";
ReactDOM.render(
<>
</>
,document.getElementById('root')
TEMPLATE LITERALS
to display Ameerpet Technologies with template literals{`${}`} using back ticks and $ symbol
const fname="Godishela";
const lname="vineeth";
ReactDOM.render(
<>
15
REACT JS
</>
,document.getElementById('root')
JSX: JSX (JavaScript XML) is a syntax extension for JavaScript used primarily with React to describe the structure of
user interfaces.
It allows developers to write HTML-like code within JavaScript, making it easier to create and manipulate UI
components.
JSX elements are transpiled into standard JavaScript before rendering in the browser.
JSX Rules
1. Single Root Element: Every JSX expression must have a single root element that encapsulates all
other elements. This is typically achieved by wrapping multiple elements in a parent
container element (e.g., <div>).
2. Event Handlers in CamelCase: Event handlers, such as onClick or onChange, should be written
in camelCase, and their values should be functions, not strings.
3. Curly Braces for Expressions: Use curly braces {} to embed JavaScript expressions within JSX.
For example, {variable} or {2 + 2}.
4. Components Start with Capital Letters: Custom components you create should begin with a
capital letter, while built-in HTML elements are in lowercase (e.g., <MyComponent /> vs. <div>).
5. No Direct HTML Entities: Avoid using HTML entities like in JSX. Use their Unicode
representations, or include them as plain text.
Specifically, it's used to convert modern JavaScript code (ES6 and beyond) into an older
version of JavaScript that is more widely supported by various web browsers.
Task:
Output:
16
REACT JS
Solution:
ReactDOM.render(<>
</>, document.getElementById('root'))
JSX ATTRIBUTES:
JSX attributes are properties or settings that you can attach to JSX elements.
JSX attributes are specified within the opening tag of an element as key-value pairs, and they
influence how the element is rendered or behaves.
Attribute Names Must Be in CamelCase: In JSX, attribute names are written in camelCase, not
in the standard HTML attribute style. For example, class in HTML becomes className in JSX.
17
REACT JS
Example1: contentEditable
ReactDOM.render(<>
</>,
document.getElementById('root'))
ReactDOM.render(<>
</>,
document.getElementById('root'))
ReactDay-5 anD 6
18
REACT JS
CSS in React:
CSS (Cascading Style Sheets) is a stylesheet language used to control the presentation and layout of web
documents.
It defines how HTML elements should appear, including colors, fonts, spacing, and positioning.
CSS rules consist of selectors that target HTML elements and property-value pairs that specify styling.
Selectors in CSS:
Whole Selector:
Element Selector:
ID Selector:
Class Selector:
BOX-Model In CSS:
The CSS Box Model consists of four layers around an HTML element: 1)Content, 2)Padding,
3)Border, and 4) Margin.
The Content layer displays the actual element's content, and its dimensions are controlled by
width and height properties.
Padding adds space between the content and the border, and its size can be adjusted using
padding properties.
The Border surrounds the padding and content, defining its thickness, style, and color.
19
REACT JS
Finally, the Margin creates space between the element and other elements on the page, and
its size is managed through margin properties.
/* Universal Selector */
*{
margin: 0;
padding: 0;
box-sizing: border-box;
/* Class Selector */
.heading {
color: red;
text-align: center;
20
REACT JS
text-transform: capitalize;
font-weight: bold;
/* Class Selector */
.imgdiv {
display: flex;
justify-content: center;
background-color: orange;
/* Element Selector */
h1 {
color: blue;
text-decoration: underline;
/* ID Selector */
#root {
Index.js
21
REACT JS
import './index.css'
ReactDOM.render(
<>
</div>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores, nulla voluptatibus
exercitationem molestias expedita dolore voluptate eaque numquam eligendi voluptates
obcaecati magni placeat.
</p>
</>
, document.getElementById('root')
);
Each property and value pair should be separated by a comma, similar to an object in
JavaScript. To make it more understandable, you should follow these steps:
1. Create a JavaScript object: Start by creating a JavaScript object that will hold your CSS
styles. This object will have key-value pairs where keys represent the CSS property in
camelCase, and values are the property values.
2. Replace styles attribute where you used div name in your previous example with this
object.
22
REACT JS
Example:
const total={
margin: 0,
padding: 0,
boxSizing: 'border-box'
const heading= {
color: 'red',
textAlign: 'center',
textTransform: 'capitalize',
fontWeight: 'bold'
const imgdiv= {
display: 'flex',
justifyContent: 'center',
backgroundColor: 'orange'
const root= {
23
REACT JS
ReactDOM.render(
<>
<div style={total}>
<div style={root}>
<div style={imgdiv}>
</div>
</div>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores, nulla voluptatibus
exercitationem molestias expedita dolore voluptate eaque numquam eligendi voluptates
obcaecati magni placeat.
</p>
</div>
</>
, document.getElementById('root')
);
Inline CSS:
In React, when writing inline CSS, you use the style attribute, and it should be enclosed in double curly braces.
24
REACT JS
The first curly brace is for JavaScript expression, and the second one is for writing CSS as an object.
Example:
ReactDOM.render(
<>
<div style={{
margin: 0,
padding: 0,
boxSizing: 'border-box'
}}>
<h1 style={{
color: 'red',
textAlign: 'center',
textTransform: 'capitalize',
fontWeight: 'bold'
<div style={{
}}>
25
REACT JS
<div style={{
display: 'flex',
justifyContent: 'center',
backgroundColor: 'orange'
}}>
</div>
</div>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores, nulla voluptatibus
exercitationem molestias expedita dolore voluptate eaque numquam eligendi voluptates
obcaecati magni placeat.
</p>
</div>
</>
, document.getElementById('root')
);
If it is morning,you should display Good Morning and it should be in green Color
If it is night,you should display Good Night and it should be in grey Color
Solution:
26
REACT JS
let greeting;
let currentTime=currentDate.getHours();
let greet;
if(currentTime>6 &¤tTime<12){
greeting="Good Mornig"
greet={
color:'green'
greet={
color:'orange'
else{
greeting="Good Night"
greet={
27
REACT JS
color:'grey'
ReactDOM.render(
ReactDay-7
React Components:
React components are the building blocks of a React application. They define how a part of the user interface should
look and behave.
They are reusable, self-contained pieces of code that define how a part of the user interface should look and behave.
React components can represent anything from simple elements like buttons and input fields to more complex
elements like entire forms or even entire pages.
There are two main types of React components: 1)functional components and 2) class components.
28
REACT JS
function HelloWorldFunctional() {
29
REACT JS
render() {
return (
<div>
</div>
);
Step 1:
Create A New File (Component) With most recommended name App.jsx in src
Now write the functional component code or Class Component code inside App.jsx as we
studied earlier in above examples
Step 2:
In Index.js
import the App (or any component which you want make it main file);
then inside the render method’s parameter write the App in angular brackets
<App/>
ReactDOM.render(
<>
30
REACT JS
<App/>
</>,document.getElementById('root'))
ReactDay-8
Javascript concept “use strict”
Preventing Undeclared Variables:
"use strict";
x = 10; // Throws an error because 'x' is not declared.
Strict mode requires strict equality checking (===) to ensure you're comparing both value and type.
"use strict";
if ("5" == 5) {
// This condition is false in strict mode because it compares a string to a number.
}
Deleting Variables:
"use strict";
var y = 5;
delete y; // Throws an error.
Duplicate Parameters:
"use strict";
function multiply(x, x) {
// Throws an error because of duplicate parameter names.
}
Octal Syntax:
31
REACT JS
"use strict";
var num = 0123; // Throws an error as octal literals are not allowed.
"use strict";
console.log(this); // 'this' is {} in the global context.
function checkThis() {
console.log(this);
}
Index.js:
import React from 'react';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
React.StrictMode:
React.StrictMode is a tool in React that you can use to highlight and catch potential problems and performance
bottlenecks in your application during development.
32
REACT JS
It wraps your entire application and activates a set of checks and warnings that are only applied in development
mode, not in production.
These checks include detecting side effects in render functions, warning about unsafe lifecycle methods, and
highlighting issues with the context API.
StrictMode is a valuable addition to your development workflow as it helps you write cleaner, more maintainable
code and ensures that your application follows best practices, ultimately improving its performance and robustness.
return (
<>
</>
);
};
In single line:
Create Two Components in src ,here I have created ComponentOne and ComponentTwo
ComponentOne.jsx
return (
33
REACT JS
<div>
<h1>I am ComponentOne</h1>
</div>
ComponentTwo.jsx
return (
<div>
</div>
App.jsx
return (<>
<ComponentOne />
<ComponentTwo /></>)
34
REACT JS
Create Two Components in src ,here I have created ComponentOne and ComponentTwo
ComponentOne.jsx
render(){
return(<>
<h1>Hello im ComponentOne</h1>
</>)
ComponentTwo.jsx
render() {
return (
<div>
</div>
App.jsx
35
REACT JS
render(){
return(<> <ComponentOne/>
<ComponentTwo/>
</>)
ReactDay -9
Export and Import Javascript topic:
Step 1: Create a Folder in Src and Name it as Components inside this Folder Create A Component As ExportImport.jsx
2)The default export is used for the primary export from the module.
3)It can be a variable, function, or component, but only one entity can be exported as the default.
4)When importing the default export in another module, you can assign it any name you like.
ExportImport.jsx
App.jsx
36
REACT JS
import message from './Components/ExportImport' //here instead of ‘message’ we can take any name as you like
see the following import hero
return (
<div>
<p>{message}</p>
<h1>{hero}</h1>
</div>
Example1:
ExportImport.jsx
var fname="Hero";
var lname="Zero"
export {fname,lname};
App.jsx
return (
37
REACT JS
<div>
<p>{message}</p>
</div>
Example 2 :instead of writing import two times we can write in single line like following
ExportImport.jsx
App.jsx
return (
<div>
<p>{message}</p>
<h1>{`${fname} ${lname}`}</h1> here we can write <h1>{fname}{lname}</h1> but we know template literals
that is why we prefer template literals process
</div>
38
REACT JS
Example3:
ExportImport.jsx
function add(a,b){
let sum=a+b;
return sum;
function sub(a,b){
let subs=a-b;
return subs;
function div(a,b){
let division=a/b;
return division;
function muul(a,b){
let multiply=a*b;
return multiply;
Here we can write the code in two ways as following you can use any process as for your requirement
Method1:
App.jsx
39
REACT JS
return (
<div>
<p>{add(5,10)}</p>
<p>{sub(10,20)}</p>
<p>{muul(9,1)}</p>
<p>{div(5,2)}</p>
</div>
Method 2:
App.jsx
import add,{ sub, div, muul } from './Components/ExportImport'; // Import named exports without 'add'
return (
<div>
<p>Add: {resultAdd}</p>
40
REACT JS
<p>Subtract: {resultSub}</p>
<p>Divide: {resultDiv}</p>
<p>Multiply: {resultMuul}</p>
</div>
);
ReactDay-10
React Component:
A React component, on the other hand, is a fundamental building block of a React application.
It's a reusable, self-contained piece of user interface that can be composed together to create
complex user interfaces.
React components are typically defined as JavaScript classes or functions and have their own state,
props, and lifecycle methods.
Components can be thought of as the UI elements of your application, like buttons, forms, lists, or
more complex structures like header bars, sidebars, and pages.
React Module:
A React module typically refers to a JavaScript file or module that contains code related to React, including React
components, utility functions, and other related code.
It's a common practice to organize React code into separate modules or files to keep the codebase organized and
maintainable.
These modules may contain multiple React components, or they can serve other purposes as well, such as defining
constants, helper functions, or Redux reducers.
MyReactModule.jsx
function Header(){
return(
41
REACT JS
<>
<h1>I am Header</h1>
</>
function IamBody(){
return(
<>
</>
function Buttons(){
return(
<>
<button>Click Me</button>
</>
function Footer(){
return(
<>
<h1>I am Footer</h1>
</>
42
REACT JS
export {Header,Buttons,Footer}
App.jsx:
function App(){
return(
<>
<Header/>
<IamBody/>
<Buttons/>
<Footer/>
</>
React Props:
React props enable data transfer from a parent component to a child component.
Props are passed as Attributes to Component and contain any type of data string,numbers,objects and even
functions.
In functional components, props are accessed as {props.propName}, while in class components, it's
{this.props.propName}.
43
REACT JS
They empower the creation of versatile and configurable user interface elements within a React application.
Example1:
PropsExamples.jsx
return (
<div>
<h1>Hello {props.name}</h1>
</div>
App.jsx
return (
<div>
<PropsExamples name="Hero"/>
</div>
44
REACT JS
Example 2:
App.jsx
return (
<div>
</div>
PropsExamples.jsx
return (
<div>
<h1>{`${props.fname} ${props.lname}`}</h1>
</div>
Sending Image url as Props and accessing it and here im also using import and export concept
of previous day
45
REACT JS
Here Create another Component with the name (ImageEx) inside PropsExample.jsx
PropsExample.jsx
return (
<div>
<h1>{`${props.fname} ${props.lname}`}</h1>
</div>
Focus on this part here we are creating another component inside the PropsExample.jsx Component
function ImageEx(props){
return(
<>
</>
export {ImageEx};
App.jsx
46
REACT JS
return (
<div>
<ImageEx imgurl="https://picsum.photos/200/300"/>
</div>
ReactDay-11
Passing Object as props in Parent Component (App.jsx)
App.jsx
return (
<div>
<Products itemobj={{
name:"Laptop",
price:25000,
mfgyr:2023,
color:'black'
}}/>
</div>
47
REACT JS
PropsExample.jsx
function Products(props){
return(
<>
<h1>Name:{props.itemobj.name}</h1>
<h1>Price:{props.itemobj.price}</h1>
<h1>Manufacturing:{props.itemobj.mfgyr}</h1>
<h1>Colour:{props.itemobj.color}</h1>
</>
export { ImageEx,Products};
App.jsx
return (
<div>
<ArrayProps itemsarray={['laptop','mobile','washingmachine','watches']}/>
</div>
48
REACT JS
Accessing array props in Child Component ArrayProps in PropsExample.jsx using map method in using paragraph
tag
function ArrayProps(props) {
return (
<>
{props.itemsarray.map((value) => {
return (
<p>{value}</p>
})}
</>
);
Accessing array props in Child Component ArrayProps in PropsExample.jsx using map method in Ordered Format
by using orderlist concept
function ArrayProps(props){
return (
<>
<ol>
{props.itemsarray.map((value,index)=>{
return (
<li key={index}>{value}</li>
49
REACT JS
})}
</ol>
</>
export {Image,Products,ArrayProps};
Accessing array props in Child Component ArrayProps in PropsExample.jsx using map method in Tabular Format
function ArrayProps(props){
return (
<>
<thead></thead>
<tbody>
<tr>
{props.itemsarray.map((value,index,arr)=>{
return(
<td key={index}>{value}</td>
)}
</tr>
</tbody>
</table>
50
REACT JS
</>
export {Image,Products,ArrayProps};
Accessing array props in Child Component ArrayProps in PropsExample.jsx using forEach method
1. Avoid using forEach in JSX; instead, use the map method to create an array of JSX
elements from props.items.
2. forEach is for iterating, not returning JSX in the JSX structure.
3. Modify your code by mapping props.items to JSX elements for proper rendering.
Although it may not be the recommended approach, I would like to provide an example in order to convey my
ideas more effectively to you.
function ArrayProps(props) {
listItems.push(<p key={index}>{value}</p>);
});
return (
<>
{listItems}
</>
);
51
REACT JS
App.jsx
return (
<div>
</div>
Childcomponent
function FunctionProps(props) {
return (
<>
<button onClick={props.afterClicking}>{props.message}</button>
</>
52
REACT JS
ReactDay-12
Props with Class Components:
return (
<div>
</div>
ClassProps.jsx
Here we use ‘this ‘ to access props in child component because class components have an instance associated with
them, and this refers to that instance.
render() {
53
REACT JS
return (
<>
</>
App.jsx
return (
<div>
<ImageClassProp imgurl="https://picsum.photos/200/300"/>
</div>
render() {
54
REACT JS
return (
<>
</>
export {ImageClassProp}
return (
<div>
<FunctionProp func={()=>9*10}/>
<ArrayProp arr={['1',2,4,6,9]}/>
</div>
export {FunctionProp,ArrayProp}
55
REACT JS
render(){
return(
<>
<h1>ans = {this.props.func()}</h1>
</>
render(){
return(
<>
<ol>
{this.props.arr.map((value,index)=>{
return <li>{value}</li>
})}
</ol>
</>
export {ImageClassProp,FunctionProp,ArrayProp}
App.jsx
56
REACT JS
return (
<div>
<ObjProp products={{
name:'hero',
age:28,
job:"software developer",
salary:'84lpa'
}}/>
</div>
ObjProp.jsx
render(){
return(
<>
<p>{this.props.products.name}</p>
<p>{this.props.products.age}</p>
<p>{this.props.products.job}</p>
<p>{this.props.products.salary}</p>
57
REACT JS
</>
export {ObjProp}
ReactDay-13
In React, "state" is a fundamental concept that plays a crucial role in building interactive and dynamic user interfaces.
State represents the data that can change over time within a component.
Each React component can have its own state, which is used to store and manage information that needs to be
rendered or updated in response to user interactions, external events, or other changes in the application.
State:
State in React is an object that holds the local data for a component.
It is used to store and manage information that can change and impact the rendering of the component.
1. State in React Class Component: State is a built-in feature that lets you store and
manage data that can change in React class components.
2. Rerendering on State Change: When state changes, React automatically updates the
component's display to reflect those changes. Changing state triggers a component re-
render.
3. Constructor and super(): When using state in a class component, you must define a
constructor and call super() within it. This setup is essential to correctly initialize the
component and inherit features from the parent class, typically Component.
In a React class component, it's a good practice to include props in both the constructor and the super() call
for two main reasons:
58
REACT JS
1. Proper Props Initialization: Including props in the constructor parameters and passing it
to super(props) ensures that your component's props are correctly initialized. This is
important for accessing the component's props within the constructor or any other
method.
2. Consistency and Clarity: While you can access this.props in methods other than the
constructor without explicitly passing props, including props in the constructor is
recommended for consistency and to make it clear that you are using props in your
component. This practice makes your code more understandable and easier to
maintain.
AllState.jsx
constructor(props){
super(props);
this.state={
data:25
render() {
return (
<div>
<p>{this.state.data}</p>
</div>
59
REACT JS
App.jsx
return (
<div>
<AllState/>
</div>
App.jsx
return (
<div>
</div>
60
REACT JS
AllState.jsx
constructor(props) {
super(props);
this.state = {
fname: props.fname,
lname: props.lname
render() {
return (
<div>
<p>FirstName={this.state.fname}</p>
<p>LastName={this.state.lname}</p>
<h1>FullName={fullname}</h1>
</div>
App.jsx
61
REACT JS
return (
<div>
</div>
AllState.jsx
constructor(props) {
super(props);
this.state = {
name: "Hero",
zero: "Zero",
FullName: this.props.fullname
changeState = () => {
render() {
62
REACT JS
return (
<div>
<button onClick={this.changeState}>ChangeTheState</button>
<p>Hero:{this.state.name}</p>
<p>Zero:{this.state.zero}</p>
<p>FullName:{this.state.FullName}</p>
</div>
Count Program:
App.jsx
return (
<div>
<AllState/>
</div>
63
REACT JS
AllState.jsx
constructor(props) {
super(props);
this.state = {
count: 0
increaseCount = () => {
render() {
return (
<>
<h1>Count:{this.state.count}</h1>
<button onClick={this.increaseCount}>increase</button>
</>
64
REACT JS
App.jsx
AllState.jsx
constructor(props) {
super(props);
this.state = {
count: 0
};
// This ensures that 'this' inside increaseCount refers to the component itself,
this.increaseCount = this.increaseCount.bind(this);
increaseCount() {
render() {
return (
<>
<h1>Count: {this.state.count}</h1>
<button onClick={this.increaseCount}>Increase</button>
65
REACT JS
</>
);
1. State is used for dynamic and changing data in a React component, and it triggers re-
renders when updated.
2. Class properties store static, unchanging data and do not trigger re-renders; they
remain constant.
3. State is managed by React, making it reactive and suitable for data affecting rendering.
4. Class properties are for constants, default values, or non-reactive data.
5. Use state for data that needs to be updated and class properties for unchanging values.
AllState.jsx
constructor(props) {
super(props);
this.state = {
name:"hello"
fullname="Ameerpet Technologies"
render() {
return (
<>
<h1>Name:{this.state.name}</h1>
<h2>FullName:{this.fullname}</h2>
66
REACT JS
</>
ReactDay-14
In React, functional components were originally introduced as stateless components, which means they didn't have
the ability to manage and maintain their own internal state.
Instead, they were meant to be purely presentational, receiving data via props and rendering it.
App.jsx:
67
REACT JS
return (
<div>
<UseStateHook/>
</div>
UseStateHook.jsx
let count=0;
const increaseCount=()=>{
count=count+1;// This will not trigger re-renders or update the component's state.
console.log("button clicked"+count);
return (
<div>
<p>Count:{count}</p>
<button onClick={increaseCount}>Increase</button>
</div>
Hooks
68
REACT JS
2. Before the introduction of hooks, state and lifecycle methods were primarily used in
class components to handle state and side effects.
3. Hooks allow you to use state and other React features in functional components
without the need for writing class components.
4. Hooks do not work in class components; they are designed for functional components.
5. Hooks should be used at the top level of functional components, not inside nested
functions or conditions, to ensure consistent behavior.
6. To use hooks, you need a Node.js version of 6 or above and npm version 5.2 or above.
7. Hooks make it easier to reuse stateful logic, manage component lifecycles, and organize your
code.
8. In React, hooks are functions that allow you to "hook into" React state and lifecycle features in
functional components.
9. They were introduced in React 16.8 to enable state management and side-effects in functional
components, which were previously only possible in class components.
useState:
useState is a React hook that allows you to add and manage state in functional components. When you call
useState in a functional component, it returns an array with two items:
1. State Object (current state): The first item in the array is the current state value.
This is the data you want to keep track of, like a number, string, object, or an array.
2. State Update Function: The second item in the array is a function that allows you to update the state.
When you call this function with a new value, React will re-render the component with the updated state.
This function is often named conventionally with "set" followed by the state variable name.
69
REACT JS
useState Syntax:
state: This is the current state value, which is initialized to initialState when the component is first
rendered.
You can access the current state value using this variable.
setState: This is a function that allows you to update the state. When you call setState with a new value,
React will re-render the component with the updated state. You can name this function whatever you
like; setState is just a commonly used convention. It can be called with a new state value to update the
state.
App.jsx
return (
<div>
<UseStateHook/>
</div>
UseStateHook.jsx
const [name]=useState('Hero')
return (
70
REACT JS
<div>
<p>Name:{name}</p>
</div>
App.jsx
return (
<div>
<UseStateHook/>
</div>
UseStateHook.jsx
setName( "Zero" );
return (
71
REACT JS
<div>
<p>Name:{name}</p>
</div>
Count Increase
App.jsx
return (
<div>
<UseStateHook/>
</div>
UseStateHook.jsx
setCount( count+1 );
return (
<div>
72
REACT JS
<p>Count:{count}</p>
</div>
Counter Component with using useState Hook and Props Concept ,Decrease(if count =0
then stop decreasing) and Reset Program
App.jsx:
return (
<div>
<UseStateHook initialnumber={5}/>
</div>
UseStateHook.jsx:
setCount( count+1 );
73
REACT JS
return (
<div>
<p>Count:{count}</p>
<button onClick={()=>setCount(0)}>Reset</button>
</div>
ReactDay-15
JavaScript Concept:
JavaScript Events:
74
REACT JS
click event
2. <!DOCTYPE html>
3. <html lang="en">
4. <head>
5. <meta charset="UTF-8">
6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
7. <title>Document</title>
8. <script>
9. function handleClick(){
10. alert("button Clicked");
11. }
12. </script>
13. </head>
14. <body>
15. <button onclick="handleClick()">click</button>
16.
17. </body>
18. </html>
MouseOver event:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function handleMouseEvent() {
alert("Hello, why are you touching me?");
}
function handleMouseUp() {
alert("Hello,You moved mouse Up");
}
</script>
</head>
<body>
<div style="background-color: blue" onmouseover="handleMouseEvent()">click</div>
<span style="background-color: gray;" onmouseup="handleMouseUp()">This is span</span>
75
REACT JS
</body>
</html>
BrowserEvents:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function loading() {
const afterLoading = document.getElementById("status");
function resizing() {
const message = document.querySelector("#status");
message.innerText = "You Resized the Window";
}
</script>
</head>
<body onload="loading()" onresize="resizing()">
<div id="status">Page is Loading...</div>
</body>
</html>
addEventListener Method:
<html lang="en">
<head>
76
REACT JS
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="mybutton">click</button>
<script>
const buttonHandle= document.getElementById('mybutton');
buttonHandle.addEventListener('click',()=>{
alert('button is Clicked and Handled by event listeners')
})
</script>
</body>
</html>
querySelector is a JavaScript method that selects the first HTML element matching a CSS selector. Use # for IDs, . for
classes, and the element name for tag names. It simplifies DOM manipulation.
Select by ID:
Select by Class:
Combining Selectors:
These examples show how to use querySelector to select elements by ID, class, tag name, and a combination of
these selectors.
77
REACT JS
getElementById is specifically for selecting elements by their ID, while querySelector can select
elements using any valid CSS selector, providing more flexibility in the selection process.
Additionally, getElementById returns the element directly, whereas querySelector returns the
first matching element or null if none is found.
MouseOverEvent:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="bluediv" style="background-color: blue" onmouseover="handleMouseEvent()">click</div>
<span class="graydiv" style="background-color: gray;" onmouseup="handleMouseUp()">This is span</span>
<script>
var graydivhandle = document.querySelector('.graydiv');
var bluedivhandle = document.querySelector('#bluediv');
graydivhandle.addEventListener('mouseup', () => {
alert("dont move mouse Up");
})
bluedivhandle.addEventListener('mouseover', () => {
alert("you are overing the mouse on me")
})
</script>
</body>
</html>
BrowserEvents:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
78
REACT JS
<body>
<div id="status">Page Loading...</div>
<script>
const mlabel = document.getElementById("status");
document.addEventListener('DOMContentLoaded', function () {
setTimeout(()=>{
mlabel.innerHTML = "Page Loaded";
},2000)
})
window.addEventListener('resize',()=>{
mlabel.innerHTML="You resized The Window";
})
</script>
</body>
</html>
1. window is the global object representing the entire browser window and includes
properties like document, location, and methods like alert().
2. document is a property of the window object, representing the HTML document loaded in
the browser, providing methods to manipulate its structure and content.
3. While window is the broader context, document specifically deals with interacting with and
modifying the content of the loaded HTML document through the Document Object
Model (DOM).
79
REACT JS
Event Object:
function handleClick(event) {
alert("Event type: " + event.type);
alert("Target element: " + event.target);
// Other event properties
}
ReactDay-16
Event Object:
80
REACT JS
The Event object is a fundamental part of the Document Object Model (DOM) and is crucial for handling interactions
and events within a web page.
The Event object represents an occurrence, such as a user clicking a button, pressing a key, resizing a window, or
any other event that can happen during the execution of a program.
The Event object provides information about the event and methods to interact with it.
Use:
When an event occurs, the browser creates an Event object and passes it as an argument to the event handler
function.
The event handler is a function that you define to specify what should happen when a particular event occurs.
The Event object contains properties that describe the event, such as the type of the event, the target element, and
additional details depending on the type of event.
preventDefault(): A method that, when called, prevents the default action associated with the event. For
example, preventing the default action of a form submission.
timeStamp: Provides the time at which the event was created, expressed in milliseconds since the epoch.
stopPropagation(): A method that stops the event from propagating up or down the DOM hierarchy,
preventing it from reaching other event listeners.
type:
By using addEventListener
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
81
REACT JS
<body>
<button id="btn">Click Me Here</button>
Enter Anything :<input type="text" id="box">
<script>
const mybutton = document.querySelector('#btn');
const textbox=document.querySelector('#box');
mybutton.addEventListener('click', function (event) {
console.log(event.type);
})
textbox.addEventListener('input',function(event){
console.log(event.type)
})
</script>
</body>
</html>
By using inlineEventHandler:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function handleButtonClick(event) {
console.log(event.type);
}
function handleInput(event) {
console.log('Input Changed and Event Type='+event.type);
}
function handleChange(event) {
console.log('Value Changed and Focus Lost and Event Type='+event.type);
}
</script>
82
REACT JS
</head>
<body>
<button onclick="handleButtonClick(event)">Click Me Here</button>
Enter Anything: <input type="text" oninput="handleInput(event)" onchange="handleChange(event)">
</body>
</html>
Target:
value:
Usage: event.target.value
Description: Used for form elements like input fields, textarea, and select. It represents the current value
entered by the user.
Example:
tagName:
Usage: event.target.tagName
Description: Returns the tag name of the element in uppercase. For example, "DIV" for a div element,
"INPUT" for an input element, etc.
Example:
id:
Usage: event.target.id
Description: Returns the id attribute of the element.
Example:
classList:
Usage: event.target.classList
Description: Returns a live DOMTokenList collection of the class attributes of the element.
83
REACT JS
Example:
javascript
const elementClasses = event.target.classList;
getAttribute():
Usage: event.target.getAttribute('attributeName')
Description: Returns the value of the specified attribute on the element.
Example:
parentNode:
Usage: event.target.parentNode
Description: Returns the parent node of the element.
Example
event.target.tagName:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="myButton">Click Me</button>
<div id="output">OutPut Will Display</div>
<script>
const ouroutput = document.getElementById("output");
const myButton = document.getElementById("myButton");
84
REACT JS
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form onsubmit="return loginHandle()">
<label>UserName</label> <input type="text" id="name" />
<label>Password</label> <input type="text" id="pswd" /></br>
<input type="submit" value="Submit">
</form>
<script>
function loginHandle() {
const UserName = document.getElementById("name").value;
const Password = document.getElementById("pswd").value;
console.log(`UserName:${UserName} PassWord:${Password}`);
return false; // Prevent form submission
}
</script>
</body>
</html>
Event.target.value
85
REACT JS
<body>
Enter Anything:<input type="text" id="box">
<script>
const boxdata=document.querySelector('#box');
boxdata.addEventListener('input',function(event){
const changed_data=document.getElementById('box').value;
console.log(changed_data)
})
</script>
</body>
Example2: By using event.target.value
<body>
Enter Anything:<input type="text" id="box">
<script>
const boxdata=document.getElementById('box');
boxdata.addEventListener('input',function(event){
const changed_data=event.target.value;
console.log(changed_data)
})
</script>
</body>
Example 3:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form id="loginForm">
<label>UserName</label> <input type="text" id="name" />
<label>Password</label> <input type="password" id="pswd" /><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("loginForm").addEventListener('submit', function (event) {
const UserName = event.target.elements.name.value;
const Password = event.target.elements.pswd.value;
console.log(`UserName: ${UserName} Password: ${Password}`);
86
REACT JS
</html>
ReactDay-17
The event.preventDefault() in the handleSubmit method prevents the default form submission
behavior, ensuring that the page doesn't reload when the user submits the form. This allows
custom logic, such as displaying an alert with the entered name and email, to execute without
losing the entered data due to a page refresh.
ReactEvents.jsx
87
REACT JS
email: ""
}
}
handleName = (event) => {
this.setState({ name: event.target.value })
console.log(this.state.name);
}
handleEmail = (event) => {
this.setState({ email: event.target.value })
console.log(this.state.email);
}
handleSubmit = (e) => {
e.preventDefault(); //if you comment out e.preventDefault() you can only see the data in alert box, but
you cannot see data in console why because page will be refreshed and data will be lost
alert(`Name:${this.state.name} Email:${this.state.email}`);
console.log(`Name:${this.state.name} Email:${this.state.email}`);
}
render() {
return (
<>
<form onSubmit={this.handleSubmit}>
<label>Name:</label><input type="text" value={this.state.name} onChange={this.handleName} />
<label>Email</label><input type="text" value={this.state.email} onChange={this.handleEmail} />
<input type="submit" value="submit" />
</form>
</>
)
}
}
export default ReactEvents;
If you comment out e.preventDefault(), the default form submission behavior will occur, causing the page to
refresh. As a result, the console.log statements in the handleName and handleEmail functions will not have a
chance to execute before the page reloads. Therefore, you won't see the data in the console because the data will
be lost during the page refresh. The alert will still work, but the logging to the console won't happen due to the
immediate page reload.
App.jsx
88
REACT JS
ReactEvents.jsx
import React, { useState } from 'react';
function ReactEvents() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const handleName = (e) => {
setName(e.target.value);
console.log(name)
}
const handleEmail = (e) => {
setEmail(e.target.value);
console.log(email)
}
const handleSubmit = (e) => {
//if you comment out e.preventDefault() you cannot see the data inside the console
//e.preventDefault();
alert(`name:${name} Email:${email}`);
console.log(`name:${name} Email:${email}`);
}
return (
<>
<form onSubmit={handleSubmit}>
89
REACT JS
}
export default ReactEvents;
ReactDay-18
Life Cycle Methods: Life cycle methods also called as SideEffects because it acts
based on actions
Realtime(side effects) when we add a product to cart ,that’s an action while performing any
action we need to perform any activity then we will use this lifecycle method so it is called side
effects
LifeCycleMethods:
If we delete any action or component will be triggered : realtime: if we remove any item from
cart then it will trigger ComponentWillUnmount():
1. constructor: This is the first method that gets called when an instance of a component is
being created. It's used for initializing state and binding methods.
2. componentDidMount: This method is called after the component has been rendered to
the screen. It's commonly used for making AJAX requests or interacting with the DOM.
90
REACT JS
3. render: This is the method that actually outputs the HTML to the DOM. It's a pure
function, meaning it should not modify component state.
4. componentDidUpdate: This method is called after the component updates, which
happens when the component's state or props change. It's often used for interacting
with the DOM or making additional AJAX requests based on the updated state or props.
5. componentWillUnmount: This method is called just before a component is removed
from the DOM. It's used for cleanup tasks, such as canceling network requests or
cleaning up subscriptions.
Initialization:
constructor()
Mounting:
render()
jsx
class MyComponent extends React.Component {
render() {
return (
// JSX representing component UI
);
}
}
componentDidMount()
91
REACT JS
Updating:
shouldComponentUpdate(nextProps, nextState)
componentDidUpdate(prevProps, prevState)
Unmounting:
componentWillUnmount()
o Invoked before a component is unmounted and destroyed.
o Used for cleanup operations.
Error Handling:
componentDidCatch(error, info)
92
REACT JS
render() {
return this.props.children;
}
}
componentDidMount() {
console.log('ComponentDidMount called');
// This method is called after the component has been added to the DOM.
// It's a good place to perform tasks like data fetching or setting up timers.
}
componentDidUpdate(prevProps, prevState) {
console.log('ComponentDidUpdate called');
// This method is called after the component's state or props have been updated.
// You can perform actions based on the previous state or props here.
}
componentWillUnmount() {
console.log('ComponentWillUnmount called');
// This method is called just before the component is removed from the DOM.
// It's a good place to clean up any resources or timers created in componentDidMount.
}
handleClick = () => {
this.setState({ message: 'New Message' });
}
93
REACT JS
render() {
console.log('Render called');
return (
<div>
<p>{this.state.message}</p>
<button onClick={this.handleClick}>Change Message</button>
</div>
);
}
}
React Day-19
UNARY OPERATOR:
Definition:
A unary operator is an operator that operates on a single operand, i.e., a single input. It
performs an operation on the operand and returns a result.
Example:
Negation (-):
let x = 5;
let y = -x; // Unary negation operator, y is now -5
Typeof Operator:
BINARY OPERATORS:
94
REACT JS
Definition:
A binary operator is an operator that operates on two operands, i.e., two inputs. It performs an
operation that combines the two operands and produces a result.
Example:
Addition (+):
javascript
let a = 5;
let b = 3;
let result = a + b; // Binary addition operator, result is 8
Multiplication (*):
javascript
let x = 4;
let y = 6;
let product = x * y; // Binary multiplication operator, product is 24
Division (/):
TERNARY OPERATOR:
Definition:
A ternary operator is a conditional operator that takes three operands: a condition followed by
two expressions. It evaluates the condition, and based on the result, it returns one of the two
expressions.
Example:
let a = 5;
let b = 8;
let max = (a > b) ? a : b; // Ternary conditional operator, max is assigned the larger of a and b
95
REACT JS
componentWillUnmount():
It will be called just before a component is about to be unmounted or removed from the DOM.
App.jsx
96
REACT JS
}
}
LifeCycleMethods.jsx
LifeCycleMethodTwo.jsx
97
REACT JS
UseEffectHook:
Purpose:
useEffect is a React Hook used for handling side effects in functional components, such
as data fetching, subscriptions, or manual DOM manipulations.
Syntax:
It takes two arguments: a function containing the code to run, and an optional array of
dependencies to control when the effect runs.
Execution Timing:
The effect function runs after the component renders, and by default, it runs after every
render. Dependencies in the array allow you to specify when the effect should run.
Cleanup:
The function returned from useEffect can be used for cleanup activities, such as
unsubscribing from subscriptions or clearing up resources when the component
unmounts.
Definition:
useEffect is a built-in React hook that allows you to perform side effects in your functional
components.
Side effects are actions that occur outside of the normal component rendering process, such as
data fetching, DOM manipulation, or setting up and cleaning up timers.
useEffect provides a way to manage these side effects in a declarative and efficient manner.
Effect function: This is a function that contains the code for the side effect you want to
perform. It's executed after the component has rendered or whenever the dependencies
specified in the second argument have changed.
98
REACT JS
Dependencies array (optional): This is an array of values that the effect depends on. When
one or more of these values change between renders
App.jsx:
When useEffect is used without a dependency array, the function inside it runs after every render of the component.
This can be useful for scenarios where you want to perform side effects on each render, such as fetching data or
updating the DOM. However, it's important to be mindful of potential performance implications and ensure that the
side effects won't cause unnecessary re-renders.
})
return (
<div>
<h1>Count:{count}</h1>
<button onClick={()=>{setCount(count+1)}}>Increase</button>
</div>
)
}
99
REACT JS
the useEffect will run once when the component mounts, and it won't run again on subsequent renders because it
has an empty dependency array. This is commonly used when you want to perform some side effect only once when
the component is initially rendered.
},[])
return (
<div>
<h1>Count:{count}</h1>
<button onClick={()=>{setCount(count+1)}}>Increase</button>
</div>
)
}
ReactDay-20
useEffect :
UseEffectExamples.jsx
100
REACT JS
Click me
</button>
</div>
);
}
export default UseEffectExamples;
Example-2:
})
return (
<div>
<p>number:{num1}</p>
<button onClick={()=>{setNum1(num1+1)}}>Increase</button>
</div>
)
}
Here, I will pass a stateobj in dependency array ex:[num1] whenever I modify the stateobj it will effect the
callbackfunction in useEffect
Here I passed num1 ,whenever I modify or update the num1 using setNum1 it will implicitily call the callback
function so that the logic inside it will be executed
101
REACT JS
return (
<div>
<p>number:{num1}</p>
<button onClick={()=>{setNum1(num1+1)}}>Increase</button>
</div>
)
}
While observing the above example, you might question the difference between removing the total
dependency array and using a dependency array where something is passed, indicating that the effect will depend
on it.
1. Dependency Tracking:
o Without a dependency array, the effect in the first example will run after every
render, including the initial render. This can lead to unnecessary executions of
the effect, especially if the effect does not actually depend on any changing
values.
o In the second example, with the dependency array [num1], the effect will only run
when num1 changes. This is more efficient and avoids unnecessary computations
if the effect only needs to be triggered when specific dependencies change.
2. Preventing Unnecessary Render Cycles:
o In the first example, without a dependency array, any state or prop changes will
cause the component to re-render, and the effect will run after each render. This
can lead to unnecessary render cycles.
o In the second example, with a dependency array, the effect will only run when
the specified dependencies change. This can prevent unnecessary re-renders and
optimize the performance of your component.
3. Readability and Intention:
o Including a dependency array explicitly communicates which values the effect
depends on. It makes the code more readable and helps other developers (or
yourself in the future) understand the purpose of the effect and its
dependencies.
o Omitting the dependency array might make it less clear whether the effect is
intentionally not dependent on any specific values or if it's an oversight.
Example 4:
Here When we Modify Num1 then only useEffect’s callback function will be called but when we modify num2 it
wont trigger callback function of useEffect
102
REACT JS
const[num2,setNum2]=useState(100);
useEffect(()=>{
alert("Hello");
},[num1])
return (
<div>
<p>number1:{num1}</p>
<p>number2:{num2}</p>
<button onClick={()=>{setNum1(num1+1)}}>Increase</button>
<button onClick={()=>{setNum2(num2-1)}}>Decrease</button>
</div>
)
}
return (
<>
<ol>
{numbers.map((cv, i) => (
<li key={i}>{cv}</li>
))}
</ol>
<button onClick={() => setNumbers([...numbers, numbers.length + 1])}>change</button>
</>
);
}
Example: useEffect
103
REACT JS
useEffect(()=>{
alert(`Array Length changed to ${numbers.length}`);
},[numbers])
return (
<>
<ol>
{numbers.map((cv, i) => (
<li key={i}>{cv}</li>
))}
</ol>
<button onClick={() => setNumbers([...numbers, numbers.length + 1])}>change</button>
</>
);
}
Example:
return (
<>
<p>{person.name}</p>
<p>{person.age}</p>
<button onClick={() => {
setPerson({ ...person,name:"Zero" })
}}>Change Name</button>
</>
);
}
Example:
104
REACT JS
ReactDay-21
App.jsx
105
REACT JS
UseReducerHookEx.jsx
useReducer:
Definition: A reducer function is a JavaScript function that takes two arguments: the current
state and an action.
};
useReducer=It provides a way to manage complex state logic in a more organized and
predictable manner. Here's an overview of useReducer
Syntax:
106
REACT JS
reducer: A function that specifies how state transitions occur based on dispatched actions.
UseReducerHookEx.jsx
UseReducerHookEx.jsx
107
REACT JS
}
export default function UseReducerHookEx() {
const initialstate = {
count: 0,
name: ""
}
const [state, dispatch] = useReducer(reducer, initialstate);
return (
<div>
<p>{state.count}</p>
<p>{state.name}</p>
<button onClick={() => dispatch({ type: "increase" })}>Increase</button>
<button onClick={() => dispatch({ type: "decrease" })}>Decrease</button>
<button onClick={() => dispatch({ type: "nameChange" })}>NameChange</button>
</div>
)
}
108
REACT JS
return (
<div>
<form onSubmit={handleSubmit}>
<label>Name:</label>
<input type="text" onChange={(e) => { setName(e.target.value) }} value={name}></input>
<label>Password:</label>
<input type="text" onChange={(e) => { setPass(e.target.value) }} value={pswrd}></input>
<input type="submit" value="submit"></input>
</form>
</div>
)
}
UseReducerHookEx.jsx
}
const initialState = {
name: "",
pswrd: ""
}
const [state, dispatch] = useReducer(reducer, initialState);
const handleSubmit = (event) => {
event.preventDefault();
alert(state.name + "" + state.pswrd)
}
return (
<div>
<form onSubmit={handleSubmit }>
109
REACT JS
<label>Name:</label>
<input type="text" onChange={(e) => dispatch({ type: "nameChange", value: e.target.value })} />
<label>Password:</label>
<input type="text" onChange={(e) => dispatch({ type: "pswrdChange", value: e.target.value })} />
<input type="submit" value="submit" />
</form>
</div>
)
}
ReactDay-22
App.jsx
import React from 'react'
import UseRefHook from './HooksTotal/UseRefHook'
UseRefHook.jsx
Example: in this example by using useState whenever we changes state it activates useEffect
because when we change the state it renders the total component .
110
REACT JS
})
return (
<div>
<h1>Your count={count}</h1>
<input type="text" onChange={(e) =>setMyData(e.target.value)} value={data}/>
</div>
)
}
useRef:
First use:
UseRefHook.jsx
})
return (
<div>
<h1>Your Number of times render={count.current}</h1>
<input type="text" onChange={(e) =>setMyData(e.target.value)} value={data}/>
</div>
)
}
111
REACT JS
useRef :
second use:
UseRefHook.jsx
const changeStyle=()=>{
console.log(input)
console.log(input.current)
return (
<div>
Example:
const[data,setMyData]=useState("");
const input=useRef(0);
const changeStyle=()=>{
112
REACT JS
input.current.style.backgroundColor="Red";
input.current.focus();
return (
<div>
Definition: Prop drilling is the process of passing data from a parent component through
intermediate child components to a deeply nested child component.
Mechanism: Parent components pass data down through props to immediate child
components, which in turn pass the data down further until it reaches the desired component
deep in the component tree.
Challenge: It can lead to increased complexity and reduced code maintainability as every
intermediate component in the hierarchy needs to accept and pass down the data even if it
doesn't use it.
App.jsx
CompA.jsx
113
REACT JS
CompB.jsx
CompC.jsx
CompD.jsx
114
REACT JS
ReactDay-23
Context API:
The Context API in React is a mechanism that allows you to share values like props between
components without having to explicitly pass the values through each level of the component
tree.
It's particularly useful when you have deeply nested components that need access to certain
values or when passing props through multiple layers becomes cumbersome.
createContext function:
The createContext function is used to create a new context. It returns an object with two
components: Provider and Consumer.
Example:
jsx
import React, { createContext } from 'react';
const MyContext = createContext();
Provider component:
The Provider component is used to wrap a part of your component tree and provide the
context values to all the components within that tree.
It takes a value prop that represents the data you want to share.
Example:
Jsx
Consumer component:
The Consumer component is used to access the context values within a component.
115
REACT JS
It uses a render prop function that receives the current context value as an argument.
Example:
jsx
<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>
here we have to use value to send data not anything other than this
CompA.jsx
116
REACT JS
CompB.jsx
CompC.jsx
CompD.jsx
This is the file(grand Child Component) where I want to consume or use the data
117
REACT JS
}}
</Fname.Consumer>
</div>
)
}
Example 2:
To send Object in single createContext:
App.jsx
CompD.jsx
118
REACT JS
return(
<h1>Hello {`FirstName = ${person.fname} and LastName = ${person.lname}`}</h1>
)
}}
</Fname.Consumer>
</div>
)
}
Example3:
App.jsx
CompD.jsx
119
REACT JS
<Fname.Consumer>
{(fname)=>{
return(
<Lname.Consumer>
{(lname)=>{
return(
<h1>{`Hello my firstname is ${fname} and my lastname is ${lname}`}</h1>
)
}}
</Lname.Consumer>
)
}}
</Fname.Consumer>
</div>
)
}
Example4:
App.jsx
CompC.jsx
120
REACT JS
This are the places or areas where you can use another Component also
CompD.jsx
121
REACT JS
ReactDay-24
useContext():
useContext is a hook in React that allows functional components to subscribe to React context without introducing
nesting.
React context provides a way to share values like themes, user authentication status, or any other global data across
components in a React application without manually passing props through every level of the component tree.
1)Creating a Context: First, you need to create a context using React.createContext. This creates a Context object
with a Provider component and a Consumer component.
Jsx
2) Providing the Context: Wrap your component tree with a Provider component. This is where you provide
the value that you want to share with components further down the tree.
jsx
// Example of providing the context
3) Consuming the Context: Now, in any child component, you can use the useContext hook to access the value
provided by the context.
jsx
function MyComponent() {
const contextValue = useContext(MyContext);
122
REACT JS
The useContext hook takes the context object as its argument and returns the current context value.
App.jsx
CompA.jsx
CompB.jsx
123
REACT JS
</div>
)
}
CompC.jsx
CompD.jsx
App.jsx
124
REACT JS
CompD.jsx
125
REACT JS
ReactDay-25
Extra Information Not Related to React.js
WWW:
The World Wide Web (WWW), commonly known as the web, is an information system that enables the sharing
and accessing of documents and multimedia content over the internet.
It was created by Sir Tim Berners-Lee in 1989 and became publicly accessible in 1991.
1. Web Pages: Documents in HTML accessible via the internet, containing text, images, links, and
multimedia elements.
2. Hyperlinks: Connect web pages, enabling users to navigate with a simple click.
3. URLs: Addresses identifying web resources, consisting of a scheme, domain, path, and optional
components.
4. Web Browsers: Software like Chrome, Firefox, Safari, enabling users to access and interact with web
content.
5. Web Servers: Computers hosting websites, responding to browser requests and delivering web pages.
6. Protocols: Standardized rules like HTTP and HTTPS facilitating communication between browsers and
servers.
7. Search Engines: Tools like Google, Bing, and Yahoo organizing web pages, helping users find specific
information
URL:
A URL, or Uniform Resource Locator, is a web address used to identify and locate resources on the internet.
It serves as a reference to access specific information, such as web pages, images, or documents.
126
REACT JS
1. Scheme: Specifies the protocol used, such as "http://" for unsecured communication or "https://" for
secure communication.
2. Host: Identifies the domain name or IP address of the server hosting the resource.
3. Port: Optionally defines the communication endpoint on the host. If not specified, the default port for the
scheme is used.
4. Path: Specifies the location or file on the server that the web server should retrieve.
5. Query Parameters: Provide additional information to the server in the form of key-value pairs, often used
for dynamic content.
6. Fragment: Identifies a specific section within the resource, commonly used in web pages.
Understanding URLs is fundamental for navigating the web and referencing specific online resources.
ReactJs:
React-router-dom:
It provides a way to navigate between different components or pages in a React application without triggering a full
page reload.
BrowserRouter is a component that uses the HTML5 history API to keep UI in sync with the URL. It provides the
foundation for client-side navigation in a React application.
You typically wrap your entire application with BrowserRouter to enable routing.
Routes:
Routes is a component that is used to define the collection of routes for your application. It serves as a container
for individual Route components.
Each Route component is declared as a child of the Routes component.
Route:
127
REACT JS
The Route component is used to declare a route and render a component when the URL matches a specified
path. It's a key building block for defining the relationship between a URL and the component you want to
render.
Link is a component used for creating navigation links. It prevents a full page reload when a link is clicked
and updates the URL using client-side navigation.
NavLink is similar to Link, but it allows you to apply styles based on whether the link is currently active.
This is useful for highlighting the active link in your navigation.
Initialisation of react-router-dom:
Command:
App.jsx
</Routes>
</BrowserRouter>
);
}
128
REACT JS
App.jsx
1. Home.jsx
2. About.jsx
3. Contact.jsx
Home.jsx
129
REACT JS
About.jsx
Contact.jsx
App.jsx
Search this url in searchbox in search engine to get Home Page :http://localhost:3000/
Search this url in searchbox in search engine to get About Page :http://localhost:3000/about
Search this url in searchbox in search engine to get Contact Page :http://localhost:3000/contact
130
REACT JS
Example:
Using ‘Link’ : in react ‘Link’ works as anchor tag ,’to’ works as href
LinksComp.jsx
131
REACT JS
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</nav>
</>
);
};
NavLink:
132
REACT JS
LinksComp.jsx
App.css
.active{
color:red;
background-color:yellow;
}
App.jsx
133
REACT JS
ReactDay-26
If page Doesn’t exist ,it should show following message
Method 1:
Home.jsx
About.jsx
134
REACT JS
Contact.jsx
LinksComp.jsx
import React from "react";
import { NavLink } from "react-router-dom";
135
REACT JS
<li>
<NavLink to="/contact">Contact</NavLink>
</li>
</nav>
</>
);
};
App.jsx
</Routes>
</BrowserRouter>
);
}
This is the only extra line we added to our previous day example
Extra Topic
136
REACT JS
You can get emojis from various sources. Here are a few options:
Method 2:
ErrorComp.jsx
function ErrorComp() {
useEffect(()=>{
document.title="🚫🛑 Error 404 (Page Not Found)";
},[])
return (
<div align="center">
<h1 >404 page Not Found</h1>
<p>Sorry, the page you are looking for might be in another castle.</p>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Possimus illo
atque error, perspiciatis officia minus maiores nam optio consequuntur
maxime, quo, dolores ex consectetur nemo! Voluptas sit veritatis
similique. Officiis.
</p>
</div>
);
}
137
REACT JS
App.jsx
</Routes>
</BrowserRouter>
);
}
Nested Route: THIS CONCEPT IS VERY RARELY USED ITS BETTER TO AVOID THIS(I'm only covering it for your
information/knowledge)
Nested routes involve placing one set of route inside another. This is achieved by using the element prop of a
<Route> to render another set of routes.
138
REACT JS
<Routes>
<Route exact path="/" element={<Home />}>
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="*" element={<ErrorComp />} />
</Route>
</Routes>
</BrowserRouter>
);
}
By doing this it wont render to other pages it will only show Home page details to avoid this
we use a Concept called Outlet
The useNavigate hook is part of the react-router-dom package that allows programmatic routing inside a React
application.
The method returns a function that can be invoked with a URI to redirect the client to the respective page.
Home.jsx
139
REACT JS
return (
<div>
<h1>Home Page</h1>
<button onClick={() => navigate("/about")}>About</button>
<button onClick={() => navigate("/contact")}>Contact</button>
</div>
);
};
Contact.jsx
</>
);
};
About.jsx
140
REACT JS
</>
);
};
App.jsx
</Routes>
</BrowserRouter>
);
}
141
REACT JS
ReactDay-27
To access Query Params in Url
But Let us See How We (The Developers) used to access the data before useParams Hooks
App.jsx
</Routes>
</BrowserRouter>
);
}
142
REACT JS
User.jsx
const User=({match})=> {
return (
<div>
<h1>Hello {match.params.name} page</h1>
</div>
)
}
export default User;
useParams: A React Router hook that provides a simple way to access parameters (route placeholders) from the
current URL within a functional component.
App.jsx
</Routes>
143
REACT JS
</BrowserRouter>
);
}
User.jsx
const User=()=> {
const {name} =useParams()
return (
<div>
<h1>Hello {name} page</h1>
</div>
)
}
export default User;
ReactDay-28
useLocation:
In React, useLocation is a hook provided by the react-router-dom library to access the current URL location.
It returns an object with information about the current URL, such as pathname, search, hash, state, and key.
App.jsx
<Routes>
<Route path="/" element={<HomeLocation />} />
<Route path="/useLoc" element={<UseLocationEx />} />
144
REACT JS
</Routes>
</BrowserRouter>
</div>
);
};
HomeLocation.jsx
UseLocationEx.jsx
console.log(location);
145
REACT JS
1)PathName
2)Search
3)hash
4)state
5)Key
JavaScript Concept
Asynchronous JavaScript and Synchronous JavaScript refer to different ways of handling code
execution and managing tasks in a JavaScript program.
Synchronous JavaScript:
Example : here every task will be started after completion of its preceding
Task A-10seconds
Task B-11seconds
Task C-15seconds
Task D-14seconds
Task E-2seconds
146
REACT JS
console.log("Start");
function doSyncTask() {
console.log("Task 1");
console.log("Task 2");
}
doSyncTask();
console.log("End");
In this example, "Task 1" and "Task 2" will be executed in order, and "End" will be logged after
the tasks are completed.
Asynchronous JavaScript:
Example : here every task Started at same Time and Works Simultaneously
Task A-10seconds
Task B-11seconds
Task C-15seconds
Task D-14seconds
Task E-2seconds
1)callbacks,
2) Promises,
147
REACT JS
Ex1:
console.log("Started");
function Asynchronous(callback) {
setTimeout(() => {
console.log("This is Asynchronus");
}, 2000);
}
Asynchronous();
console.log("Ended");
Ex2:
console.log("Started");
function Asynchronous(callback) {
setTimeout(() => {
console.log("This is Asynchronus");
}, 2000);
callback();
}
Asynchronous(() => {
console.log("CallBack Called");
});
console.log("Ended");
In this example, "Async Task" will be logged after a delay of 1000 milliseconds, but the
program doesn't wait for it. The "End" will be logged immediately after initiating the
asynchronous task, and "Callback executed" will be logged after the asynchronous task
completes.
Asynchronous JavaScript is commonly used in web development to handle tasks like making AJAX
requests, handling user input, and performing other non-blocking operations to ensure a
smoother user experience.
Trick: if you find this in code then that code is Asynchronous Code
1. setTimeout,
2. setInterval,
148
REACT JS
3. Promises,
4. Callbacks,
5. fetch,
6. axios,
7. and XMLHttpRequest
Note:
1)Synchronous Always Code Moves to Main Stack(call Stack) {the code in mainStack runs(executes) first}
2)Asynchronous Always Code Moves to SideStack(callback queue) {the code in sideStack processes after processing
it moves to sideStack}
Call Stack: The call stack is a data structure that keeps track of function calls in a program. It is used for managing
the flow of synchronous code.
When a function is called, a new frame is added to the top of the call stack, and when the function completes, its
frame is removed.
The call stack is used for synchronous execution and follows the Last In, First Out (LIFO) principle.
Callback Queue: The callback queue is part of the asynchronous execution model. It holds callbacks or events
that are produced as a result of asynchronous operations such as timers, network requests, or user interactions.
When an asynchronous operation is completed, its callback function is placed in the callback queue.
The event loop constantly checks the callback queue, and when the call stack is empty, it takes the first callback
from the queue and pushes it onto the call stack for execution.
console.log("Started");
setTimeout(() => {
console.log("This is Asynchronous");
}, 0);
console.log("Ended");
output:
Started
Ended
This is Asynchronous
149
REACT JS
Callback function : it will be executed when asynchronous code’s logic is completed ( or) it is intended to be executed
after the completion of an asynchronous operation.
ReactDay-29
In JavaScript, a promise is an object that represents the eventual completion or failure of an
asynchronous operation and its resulting value.
Promises are a way to work with asynchronous code in a more organized and readable manner.
They provide a cleaner and more structured alternative to using callbacks.
Creation of Promises:
You can create a promise using the Promise constructor, which takes a function as an argument.
These are functions that you call to indicate the success or failure of the asynchronous operation.
// Asynchronous operation
});
STATES OF A PROMISE:
Pending: The initial state; the promise is neither fulfilled nor rejected.
Fulfilled: The operation completed successfully, and the promise has a resulting value.
Rejected: The operation failed, and the promise has a reason for the failure.
150
REACT JS
CONSUMPTION OF PROMISES:
The .then() method is called when the promise is fulfilled, and it receives the resolved value. The
.catch() method is called when the promise is rejected, and it receives the reason for the
rejection
myPromise
.then((result) => {
// Handle successful operation
console.log(result);
})
.catch((error) => {
// Handle error
console.error(error);
});
CHAINING:
javascript
const promise1 = new Promise(/* ... */);
promise1
.then((result) => {
// Do something with the result
return result * 2;
})
.then((result) => {
// Do something with the new result
console.log(result);
})
.catch((error) => {
// Handle errors in any part of the chain
console.error(error);
});
Example1:
//creating Promise
const prom = new Promise((resolve, reject) => {
let a = 1 + 1;
if (a === 2) {
resolve("True or Successfully resolved");
151
REACT JS
} else {
reject("false or Promise rejected");
}
});
//Accessing Promise
prom
.then((data) => {
console.log("Ans=" + data);
})
.catch((data) => {
console.log("Ans=" + data);
});
Example 2:
With using the Callbacks
const notlistening=true;
const usingmobile=true;
function listenClassProperly(listeningcallback,notlisteningcallback){
if(notlistening){
notlisteningcallback({
name:"you are not listening the class",
message:"so please listen the class "
})
}
else if(usingmobile){
notlisteningcallback({
name:"you are using mobile phone in the class",
message:"so please stop scrolling"
})
}
else{
listeningcallback("Thank You Listening the class Properly");
}
}
listenClassProperly((response)=>{
console.log(response)
},(error)=>{
console.log(error.name+","+error.message)
})
Example 3:
Converting above example to Promises
152
REACT JS
listenClassProperlyPromise()
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.name + "," + error.message);
});
ReactDay-30
Ajax, which stands for Asynchronous JavaScript and XML, is a set of web development
techniques that allows web applications to send and receive data from a server asynchronously.
The key components of Ajax are:
153
REACT JS
1. Asynchronous: Ajax allows web pages to make requests to the server and retrieve data
in the background without requiring a full page reload. This asynchronous nature allows
for a more dynamic and responsive user experience.
2. JavaScript: Ajax uses JavaScript to make asynchronous requests to the server and
manipulate the Document Object Model (DOM) dynamically based on the received data.
JavaScript plays a crucial role in updating the content of the web page without requiring
a complete reload.
3. XML (or JSON): Traditionally, XML was used as the data interchange format in Ajax, but
JSON (JavaScript Object Notation) has become more popular due to its simplicity and
ease of use. JSON is now the preferred data format for most Ajax applications
4. Event Triggering: An event, such as a button click or a timer, triggers an Ajax request
from the web page.
5. Asynchronous Request: Using JavaScript, the web page sends an asynchronous request
to the server. This request is typically made using the XMLHttpRequest object in modern
browsers or the fetch API.
6. Server Processing: The server processes the request and sends back the requested data.
This data is commonly in JSON format but can also be XML or other formats.
7. Asynchronous Response: The web page receives the response asynchronously.
JavaScript handles the response and updates the DOM without reloading the entire
page.
Fetch Method(fetch()):-
fetch() is a modern JavaScript API for making network requests (HTTP requests) in web browsers.
It provides a more flexible and powerful way to interact with web servers compared to the older XMLHttpRequest
object.
The fetch() function returns a Promise that resolves to the Response to that request, whether it is successful or not.
Parameters:
response.status: The HTTP status code is a three-digit code indicating the result of the server's attempt to process
the request. Common HTTP status codes include 200 for a successful request, 404 for not found, and 500 for server
errors.
154
REACT JS
response.ok: Checks if the HTTP status of the response is within the successful range (200 to 299).
Example1:
200
True
An object is a fundamental data structure in programming languages, representing entities with properties and
methods. JSON, or JavaScript Object Notation, is a lightweight text-based data interchange format, often used for
data exchange between systems or as a configuration format, with a strict syntax and no support for function
The json() method is used to extract the JSON body content from the HTTP response and parse it into a JavaScript
object.
Pending state:
const url="https://data.covid19india.org/v4/min/data.min.json";
fetch(url).then((response)=>{
console.log(response.status);
console.log(response.ok);
console.log(response)
console.log(response.json())
})
Throw Error: If the status is not within the successful range, it throws an error. This is a way to handle cases where
the server might respond with an error status (e.g., 404 Not Found).
Method1:
155
REACT JS
Method 2:
const url="https://data.covid19india.org/v4/min/data.min.json";
fetch(url).then((response)=>{
return response.json()
}).then((data)=>{
console.log(data)
}).catch((error)=>{
console.log(error)
})
In JavaScriptPractice Folder
1)Create fetchFile.html
fetchFile.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="Asynchronous.js"></script>
156
REACT JS
</head>
<body>
</body>
</html>
Asynchronous.js
Specific Data:
Asynchronous.js
Using Authentication:
157
REACT JS
fetch('https://climate-news6.p.rapidapi.com/news/HindustanTimes', {
method: 'GET', // or 'POST' or other HTTP methods
headers: {
'X-RapidAPI-Key': '7dca06e799msh08f5d6b6a3538d8p1a1411jsn8d50a91dfcfd',
'X-RapidAPI-Host': 'climate-news6.p.rapidapi.com'
}
})
.then(response => {
console.log(response.status);
console.log(response.ok)
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
ReactDay-31
Asynchronous programming is often used in scenarios where certain operations, such as I/O
operations or network requests, might take some time to complete, and you don't want the
entire program to be blocked while waiting for these operations.
In languages like Python and JavaScript, the async and await keywords are used to work with
asynchronous code. Here's a brief explanation of these keywords:
await: This keyword is used inside an asynchronous function to wait for the completion
of another asynchronous operation.
It can only be used inside an async function.
158
REACT JS
When you use await before a promise, it pauses the execution of the function until the
promise is resolved, and then it resumes with the result.
async/await is built on top of promises and provides a more concise and synchronous-looking
syntax for handling asynchronous operations.
It tends to make asynchronous code easier to read and reason about, especially for
developers who are more accustomed to synchronous programming styles.
With async/await, you can write asynchronous code that looks similar to synchronous code,
making it more approachable and potentially reducing the chances of introducing errors.
Example 1:
Example 2:
Example 3:
159
REACT JS
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
React Js
What is Axios?
Axios is a popular JavaScript library that simplifies the process of making HTTP requests.
Axios is widely used for tasks such as fetching data from APIs, sending data to servers, and
handling responses.
1. Simplicity: Axios provides a straightforward and consistent API, making it easier to work
with compared to the native fetch API.
2. Automatic JSON Parsing: Axios automatically parses JSON responses, saving you from
manually parsing data retrieved from APIs.
3. Interceptors: Axios supports interceptors, allowing you to globally handle requests and
responses. This is useful for tasks like authentication, logging, or error handling.
160
REACT JS
1. Install Axios:
o You need to install Axios. If you're using Node.js, you can do this using npm or
yarn
yarn add axios
Import Axios:
import Axios:
// CommonJS
const axios = require('axios');
// ES6 Modules
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => {
console.log('Data:', response.data);
})
.catch(error => {
console.error('Error:', error);
});
161
REACT JS
});
Using Async/Await:
fetchData();
Fetching Data from APIs: When you need to retrieve data from a web server.
Sending Data to Servers: When you want to send data to a server, typically as part of a
form submission or updating resources on the server.
Handling API Responses: When you need to handle the responses from APIs, including
error handling, data processing, and rendering.
In Frontend Frameworks: Axios is commonly used in frontend frameworks like React,
Angular, or Vue to manage HTTP requests.
axios
.get("https://data.covid19india.org/v4/min/data.min.json")
.then((res) => {
console.log(res.data);
162
REACT JS
setState(res.data);
});
return (
<div>
<h1>Axios</h1>
<h1>
{state.map((cv) => {
return <li key={cv.id}>{cv}</li>;
})}
</h1>
</div>
);
}
Example 2:
import React, { useState } from "react";
import axios from "axios";
export default function AxiosEx() {
const [state, setState] = useState([]);
axios
.get("https://data.covid19india.org/v4/min/data.min.json")
.then((res) => {
console.log(res.data);
const arrayKey = Object.keys(res.data);
setState(arrayKey);
});
return (
<div>
<h1>Axios</h1>
<ol>
{state.map((cv) => {
return <li key={cv.id}>{cv}</li>;
})}
</ol>
</div>
);
}
163
REACT JS
Example3:
import React, { useState, useEffect } from "react";
import axios from "axios";
// AxiosEx component to fetch and display COVID-19 data for Indian states
export default function AxiosEx() {
// State to store Indian states
const [indianStates, setStates] = useState({});
// Make an asynchronous request to fetch COVID-19 data when the component mounts
useEffect(() => {
// Axios GET request to the COVID-19 data API for India
axios
.get("https://data.covid19india.org/v4/min/data.min.json")
.then((response) => {
// Extract district keys from the state of Telangana (TG)
const keys = Object.keys(response.data.TG.districts);
// The empty dependency array ensures that this effect runs only once when the component mounts
}, []);
{/* Display the list of Indian states using an ordered list */}
<ol>
{/* Map through the Indian states and display them as list items */}
{indianStates.map((state, i) => {
return <li key={i}>{state}</li>;
})}
</ol>
</>
);
}
164
REACT JS
ReactDay-32
Vanilla
Vue
Preact
Lit
Svelte
Solid
Qwik
Others
TypeScript
TypeScript + SWC
> JavaScript
165
REACT JS
JavaScript + SWC
cd react-with-vite
npm install
found 0 vulnerabilities
166
REACT JS
Folder Structure:
167
REACT JS
As of my last knowledge update in January 2022, Vite and React are two separate tools that serve
different purposes in the web development ecosystem. React is a JavaScript library for building
user interfaces, while Vite is a build tool that aims to provide a faster development experience
for web applications.
1. Purpose:
o React: React is a JavaScript library developed by Facebook for building user
interfaces. It provides a declarative syntax for describing how the UI should look,
168
REACT JS
and it efficiently updates and renders components when the application state
changes.
o Vite: Vite is a build tool that focuses on providing a fast development server and
a build system optimized for modern JavaScript frameworks, including React. It is
not a framework like React; rather, it's a tool that can be used with different
frameworks.
2. Development Server:
o React: React applications are often created using tools like Create React App
(CRA), which includes a development server for local development.
o Vite: Vite comes with its own development server that leverages native ES
module imports to achieve fast module resolution and hot module replacement
(HMR) for quick feedback during development.
3. Build Performance:
o React: Traditional React applications use tools like Webpack for bundling and
optimizing code for production. The build process might take longer as the
application grows.
o Vite: Vite aims to provide faster build times by leveraging ES module imports and
pre-bundling dependencies during development. This can result in quicker builds
compared to traditional bundlers like Webpack.
4. Configuration:
o React: Tools like Create React App abstract away much of the configuration
complexity, providing a pre-configured setup out of the box. Advanced
configurations can be ejected for more customization.
o Vite: Vite promotes a "zero-config" setup for common scenarios, meaning you
can get started without a complex configuration file. However, it allows you to
customize configurations when needed.
5. Ecosystem:
o React: React has a large and mature ecosystem with a vast number of libraries,
tools, and community support.
o Vite: While Vite itself is not a framework and doesn't dictate the choice of
frontend library or framework, it's often used with modern frameworks like
React, Vue, or Svelte. The Vite ecosystem is growing as more developers adopt
it.
It's worth noting that the information provided is based on my knowledge as of January 2022,
and there may have been updates or changes to React, Vite, or their ecosystems since then.
Always refer to the official documentation for the most up-to-date information.
Exam :
Coding Questions js
169
REACT JS
React Js Questions
1. What is React?
2. Features of Reactjs? Write 3 commands to create react app
3. Difference between Class Component and Functional Component?
4. Draw the diagram of React flow ? Explain use of Each Component in the Flow?
5. What is Jsx and State Jsx rules?
6. What is Props?Pass the OBJECT from Parent component and Display it on
ChildComponent{use Class Component}
7. Pass the ARRAY from Parent component and Display it on ChildComponent{use
Functional Component}
8. Explain Props Drilling?How to overcome PropsDrilling?
9. Define State and Write Counter Program using Class Component?
10. Create a Login Form and Store Data and Display in Console?{hint:useState and
eventhandlers}
11. Explain lifecycle Methods with Example?
12. Explain the use Of useEffect with Example
13. List known hooks and Write a program using useContext hook?
14. Write the use of react-router-dom and explain with example?
15. Define useNavigate,useParams,useLocation?
170
REACT JS
ReactDay-33
Flux:
In React, "flux" typically refers to a design pattern for managing the flow of data in a React
application. It is not a built-in feature of React itself, but rather an architectural pattern that
complements React's component-based structure. The Flux pattern is often used to handle state
management and data flow in a unidirectional manner, making it easier to reason about and
maintain large applications.
The basic idea behind Flux is to have a unidirectional data flow, where data flows in a single
direction through the application. There are several key components in the Flux architecture:
1. Actions: These are plain JavaScript objects that represent something that has happened
in the application. They are created by different parts of your application (such as user
interactions) and provide a way to signal to the rest of the system that a change is
needed.
2. Dispatcher: The dispatcher is a central hub that manages the flow of data in a Flux
application. It receives actions and dispatches them to registered stores.
3. Stores: Stores contain the application state and logic. They register with the dispatcher
to receive actions and update their state accordingly. When a store's state changes, it
triggers a change event.
4. Views (React Components): React components are responsible for rendering the user
interface based on the current state of the stores. They listen to changes in the stores
and update themselves accordingly.
5. In the context of React.js, "Flux" might refer to the Flux architecture, which is a pattern
for managing data flow in a React application. However, it's essential to note that Flux
itself doesn't require a separate installation as it is a pattern, not a library or a tool.
Instead, it's a set of principles for managing state in a predictable way.
6. If you're looking for state management solutions in a React application, you might
consider using libraries like Redux, MobX, Recoil, or the built-in Context API. These
libraries help you implement the Flux architecture or other state management patterns.
Redux:
Redux is a predictable state container for JavaScript applications, primarily used with libraries like React
for building user interfaces.
171
REACT JS
It follows the Flux architecture and provides a unidirectional data flow, making it easier to
manage the state of an application in a predictable and centralized manner.
Redux is not tied to any specific framework and can be used with other libraries as well.
WHAT IS REDUX?
Redux is a pattern and library for managing and updating application state, using events called
"actions". It serves as a centralized store for state that needs to be used across your entire application,
with rules ensuring that the state can only be updated in a predictable fashion.
Redux helps you manage "global" state - state that is needed across many parts of your application.
The patterns and tools provided by Redux make it easier to understand when, where, why, and how
the state in your application is being updated, and how your application logic will behave when those
changes occur. Redux guides you towards writing code that is predictable and testable, which helps give
you confidence that your application will work as expected.
Redux helps you deal with shared state management, but like any tool, it has tradeoffs. There are more
concepts to learn, and more code to write. It also adds some indirection to your code, and asks you to
follow certain restrictions. It's a trade-off between short term and long term productivity.
You have large amounts of application state that are needed in many places in the app
The app state is updated frequently over time
The logic to update that state may be complex
The app has a medium or large-sized codebase, and might be worked on by many people
Not all apps need Redux. Take some time to think about the kind of app you're building, and decide
what tools would be best to help solve the problems you're working on.
1. Store:
172
REACT JS
o The central piece of Redux is the store, which holds the entire state of the
application.
o The state is read-only, and the only way to change it is by dispatching actions.
2. Actions:
o Actions are plain JavaScript objects that represent an intention to change the
state.
o Actions must have a type property that describes the type of action being
performed.
o Actions can also carry additional data (payload) that is necessary for the state
change.
3. Reducers:
o Reducers are pure functions that take the current state and an action as
arguments and return a new state.
o Reducers specify how the state changes in response to actions.
o Each reducer typically handles a specific part of the state.
4. Dispatch:
o Actions are dispatched to the store using the dispatch method.
o When an action is dispatched, the store calls the corresponding reducer, and the
state is updated accordingly.
5. Selectors:
o Selectors are functions that retrieve specific pieces of data from the state.
o They help in efficiently extracting information from the state in a consistent
manner.
6. Middleware:
o Middleware provides a way to extend Redux with custom functionality.
o It sits between the dispatching of an action and the moment it reaches the
reducer.
o Common use cases for middleware include logging, asynchronous operations,
etc.
1. Action Creation:
Reducer:
173
REACT JS
Store Creation:
Dispatching Actions:
javascript
store.dispatch(increment());
State Retrieval:
javascript
5. const currentState = store.getState();
Redux is commonly used with React, and the react-redux library provides bindings to connect
Redux with React components, allowing them to access the state and dispatch actions easily.
Remember that while Redux can be powerful for managing the state of large and complex
applications, it might introduce unnecessary complexity for smaller applications. It's often
recommended to evaluate your specif
the command npm install redux react-redux is correct for installing the Redux library and the React bindings for
Redux.
This command installs both the core Redux library (redux) and the React bindings (react-redux) that are used to
integrate Redux with React applications.
174
REACT JS
index.js
updown.js
index.js
store.js
175
REACT JS
const globalstore=createStore(mainReducer);
export default globalstore;
or
import { configureStore } from "@reduxjs/toolkit"; // Make sure to import from the correct path
import mainReducer from "./Reducersss/index";
App.jsx
useSelector is a Selector
return (
<div>
<button
onClick={() => {
// Dispatch your action here
dispatch(deCrement ());
}}
>
-
</button>
<input type="text" value={myState} readOnly />
<button
176
REACT JS
onClick={() => {
// Dispatch your action here
dispatch( inCrement());
}}
>
+
</button>
</div>
);
}
Main.jsx
Redux : https://redux.js.org/
177
REACT JS
tHanK - yOU
178