0% found this document useful (0 votes)
91 views

React js

Uploaded by

abhimanyu thakur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

React js

Uploaded by

abhimanyu thakur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 179

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,

is an open-source JavaScript library for building user interfaces.

React is a robust and widely-used JavaScript library for developing streamlined, interactive Single Page
Applications (SPAs).

 It was developed by Facebook, and its development began in 2011.

React was introduced by Jordan Walke, a software engineer at Facebook.

He initiated the development of React while working at Facebook, and the project was open-
sourced by Facebook in May 2013.

In MVC (Model,View,Controller) architecture Reactjs plays the role of view

History Of ReactJs:

React started development at Facebook in 2011.

Open-sourced by Facebook in May 2013.

Introduced the Virtual DOM concept for efficient UI updates.

Promotes a component-based architecture for UI development.

React Native introduced in 2015 for mobile app development.

Major rewrite called React Fiber in 2016 for improved performance.

Experimental feature Concurrent Mode in 2018 for better responsiveness.

React 17 (2020) focused on gradual updates and compatibility.

Continues to be actively developed and widely used in web development.

Features of ReactJs:

1
REACT JS

Component-Based Architecture: React encourages a component-based approach to UI


development. This allows you to break your UI into small, reusable components, making it easier
to manage and maintain code. Each component can have its own HTML, CSS, and JavaScript logic.

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.

Create React Application:


1)install vs code

2) install node

3)open command prompt and enter following commands

node –version (if it shows any version then node is installed successfully)

npm –version (if its shows any version then npm is installed successfully)

otherwise download again by uninstalling it and reinstall

2
REACT JS

4)create a folder on desktop

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

7)it gives a dropbox ,click Terminal then click new Terminal

8)inside new terminal write the following command to create react app

naming rules for your 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

npx create-react-app react-batch-two

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."

create-react-app is a tool of npm used to create the react application

react-batch-two is your Project or Application name

It will Take Some Time Then

4
REACT JS

Now change directory cd react-batch-two

Then npm start

It runs on default localhost :3000

Your App SuccessFully Loaded

if above Command Doesn’t Work go with any One Of the Command

1)npx create-react-app react-batch-two (or)

2)npm init react-app react-batch-two (or)

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

write the following command create-react-app react-batch-two


Folder Structure of React:-

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.

Styles and CSS Files:

index.css: Global CSS styles for your application.


App.css: Styles specific to the main "App" component.

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 (Node Package Manager):

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 (Node Package Runner):

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

2)index.html is the root file which will display on webpage

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

4)Next delete the content of the index.js

here we will write code and we will send to index.html

9
REACT JS

Old way of using React-js :-


write the following code in index.js

Method1:- We are using pure javascript or dom manipulation and displaying the message on
Browser

var message=document.createElement('h1'); //creating an element

message.innerHTML="hello Ameerpet Technologies"; //adding value to the created element

document.getElementById('root').appendChild(message) ; // add an Html element (by using this sending value to


index.html 's div tag which has id as root)

In the "Old way of React-js," you manually create and manipulate HTML elements using JavaScript, without JSX or
the convenience of React components

Pure JavaScript DOM Manipulation:

10
REACT JS

Instead of using React components and JSX, you create and manipulate HTML elements directly using pure
JavaScript.

1. Creating HTML Elements:


o You use JavaScript to create HTML elements, set their properties (e.g., innerHTML), and
attributes.
2. Appending Elements:
o After creating an element, you append it to the DOM by selecting an existing element (in your
example, an element with the ID 'root') and using methods like appendChild.
3. No React Library:
o In this approach, you don't use the React library or ReactDOM to render components. You're
essentially working with plain JavaScript and the DOM.

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.

Method2:- with using react and react-dom

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.

2. react-dom : react-dom is a package that is part of the React ecosystem.

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

The render method takes three parameters:

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()

ReactDOM.render(<h1>Hello Heros</h1>, document.getElementById('root'), ()=> {

// This is the callback function that will be executed after rendering is complete.

console.log('Rendering is complete.');

}); here html tag (<h1></h1>)what to show,

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).

Method 3: by importing react and react-dom

// Import the necessary libraries such as ‘react’ and 'react-dom’

import React from 'react';

import ReactDOM from 'react-dom';

// Render an "h1" element with the text "HELLO HEROS" into the HTML element with the ID 'root'

ReactDOM.render(

<h1>Welcome to React World</h1>, document.getElementById('root')

);

---------------------------------------------------------------------------------------------------------

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:

1. Wrapping in a Single <div> Tag:

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.

2. Wrapping in a Fragments (<> </> or <React.Fragment> </React.Fragment>):

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.

(Html lo Js use cheyyalantey  { } use cheyyali)

 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)

Just understand with diagram

JavaScript
JSX(HTML)
{JavaScript}

Example 1:

import React from 'react'

import ReactDOM from 'react-dom'

const fname="Ameerpet ";

const lname="Technologies";

ReactDOM.render(

<>

<h1>HELLO {fname}</h1>

<p>Hello {lname}</p>

<p>sum ={1+6}</p></>

,document.getElementById('root')

Example2:To write Ameerpet Technologies(any name)

14
REACT JS

import React from 'react'

import ReactDOM from 'react-dom'

const fname="Ameerpet";

const lname="Technologies";

ReactDOM.render(

<>

<h1>HELLO {fname +" "+lname}</h1>

<h1>Hello {fname} {lname}</h1>

</>

,document.getElementById('root')

TEMPLATE LITERALS

to display Ameerpet Technologies with template literals{`${}`} using back ticks and $ symbol

import React from 'react'

import ReactDOM from 'react-dom'

const fname="Godishela";

const lname="vineeth";

ReactDOM.render(

<>

<h1>{`hello ${fname} ${lname}`}</h1>

<h1>Hello {fname} {lname}</h1>

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 &nbsp; in JSX. Use their Unicode
representations, or include them as plain text.

Babel: Babel is often referred to as a "transpiler" because it performs source code


transformation from one version of JavaScript to another.

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.

 This process is known as "transpilation" (short for "source-to-source compilation").

just try in babel.com

Task:

Output:

16
REACT JS

Hello My Name is “Your Name” I am from “Location”

Today’s Date is Wed Oct 18 2023

Now Time is 23 : 48 : 23 (“Present time in your system”)

Solution:

import React from 'react'

import ReactDOM from 'react-dom'

const name = "Hero"

const loc = "Hyderabad"

const date = new Date();

ReactDOM.render(<>

<h1>{`My Name is ${name} i am from ${loc}`} </h1>

<p>{`Today's Date is ${date.toDateString()}`}</p>

<p>{`Today's Date is ${date.toLocaleDateString()}`}</p>

<p>{`Now Time is ${date.getHours()} : ${date.getMinutes()} : ${date.getSeconds()}`}</p>

</>, document.getElementById('root'))

JSX ATTRIBUTES:

JSX attributes are properties or settings that you can attach to JSX elements.

They provide additional information about an element or configure its behavior.

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

import React from 'react'

import ReactDOM from 'react-dom'

const name = "Hero"

const loc = "Hyderabad"

ReactDOM.render(<>

<h1 contentEditable="true">{`My Name is ${name} i am from ${loc}`} </h1>

</>,

document.getElementById('root'))

Example 2: using img tag

import React from 'react'

import ReactDOM from 'react-dom'

const name = "Hero"

const loc = "Hyderabad"

ReactDOM.render(<>

<h1 contentEditable="true">{`My Name is ${name} i am from ${loc}`} </h1>

<img src="https://picsum.photos/200/300" alt="Random" />

</>,

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.

Styles can be applied inline, in the document head, or in external files.

Selectors in CSS:

Whole Selector:

o The wildcard selector (*) selects all HTML elements on a page.


o How to write: * { ..... }

Element Selector:

o Selects all HTML elements of a specific type (e.g., <p>, <h1>).


o How to write: elementname { ..... }, e.g., p { ... ..}.

ID Selector:

o Selects a single element with a specific ID attribute.


o How to write: #idname { ..... }, e.g., #header { ..... }.

Class Selector:

o Selects elements with a specific class attribute.


o How to write: .classname { ... }, e.g., .highlight { ..... }.

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.

External css example:


Write css code index.css

/* 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 {

border: 2px solid green;

Index.js

import React from 'react';

import ReactDOM from 'react-dom';

21
REACT JS

import './index.css'

const name = 'Hero'; // Replace with the desired name

ReactDOM.render(

<>

<h1 contentEditable="true">Hello Hero {name}</h1>

<h1 className="heading">Hello Hero {name}</h1>

<div id="root" className="imgdiv">

<img src="https://picsum.photos/200/300" alt="randomimages" />

</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')

);

INTERNAL CSS:- Here we should write css in object format

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:

import React from 'react';

import ReactDOM from 'react-dom';

const name = 'Hero'; // Replace with the desired name

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= {

border: '2px solid green'

23
REACT JS

ReactDOM.render(

<>

<div style={total}>

<h1 contentEditable="true">My Name is editable {name}</h1>

<h1 style={heading}>Our office head is {name}</h1>

<div style={root}>

<div style={imgdiv}>

<img src="https://picsum.photos/200/300" alt="randomimages" />

</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:

import React from 'react';

import ReactDOM from 'react-dom';

const name = 'Hero'; // Replace with the desired name

ReactDOM.render(

<>

<div style={{

margin: 0,

padding: 0,

boxSizing: 'border-box'

}}>

<h1 contentEditable="true">My Name is editable {name}</h1>

<h1 style={{

color: 'red',

textAlign: 'center',

textTransform: 'capitalize',

fontWeight: 'bold'

}}>Our office head is {name}</h1>

<div style={{

border: '2px solid green'

}}>

25
REACT JS

<div style={{

display: 'flex',

justifyContent: 'center',

backgroundColor: 'orange'

}}>

<img src="https://picsum.photos/200/300" alt="randomimages" />

</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')

);

Task using css

If it is morning,you should display Good Morning and it should be in green Color

 If it is afternoon,you should display Good AfterNoon and it should be in orange Color

If it is night,you should display Good Night and it should be in grey Color

Solution:

import React from 'react'

26
REACT JS

import ReactDOM from 'react-dom'

let greeting;

//let currentDate=new Date();//it gives you system or machine time defaultly

let currentDate=new Date(2023,10,19,13); //we can set the time year/month/date/time-24hrs-


format

let currentTime=currentDate.getHours();

let greet;

if(currentTime>6 &&currentTime<12){

greeting="Good Mornig"

greet={

color:'green'

else if(currentTime>=13 &&currentTime<18){

greeting ="Good AfterNoon"

greet={

color:'orange'

else{

greeting="Good Night"

greet={

27
REACT JS

color:'grey'

ReactDOM.render(

<h1>HEllo<span style={greet}> { greeting}</span></h1>,document.getElementById('root')

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.

Difference Between Class and Funtional Component:

Aspect Class Components Functional Components


Syntax Defined as JavaScript classes. Defined as JavaScript functions.
Can have their own internal Do not have their own internal
State Management
state using this.state. state.
Can use lifecycle methods for
Cannot use lifecycle methods
Lifecycle Methods side effects and state
(e.g., componentDidMount).
management.
Manage side effects within
Manage side effects using hooks
Side Effects lifecycle methods (e.g.,
(e.g., useEffect).
componentDidMount).
More complex and verbose,
Simpler and more concise,
Simplicity especially when dealing with
especially with hooks.
lifecycle methods.
Reusable but requires more
Reusability Easy to reuse and compose.
code for setup.

28
REACT JS

Often referred to as "class" or Often referred to as "functional"


Type of Component
"stateful" components. or "stateless" components.
Lifecycle methods in class Hooks provide a consistent way
Syntax Consistency components may vary in usage to handle state and side effects
and syntax. across components.
May have slightly more
Generally performs better due
Performance overhead due to the class
to less overhead.
structure.
Steeper learning curve,
Easier for beginners to grasp,
Learning Curve especially for those new to
especially with hooks.
JavaScript classes.
Not required to create classes;
Requires the creation of a class
Class Usage can use arrow functions or
with class syntax.
named functions.
this keyword is used to access
this keyword is not used within
this Keyword component properties and
functional components.
methods within class compon
HOCs were more commonly Can use HOCs but not as
HOCs (Higher Order
used for code reuse in class commonly needed due to
Components)
componen hooks.
State is initialized within the
State can be initialized using the
State Initialization constructor of a class
useState hook.
component.
Access and handle props using Access and handle props as
Props Handling this.props within class arguments to the functional
components. component.

Syntax of Functional Component:

import React from 'react';

function HelloWorldFunctional() {

return <div>Hello, World! (Functional Component)</div>;

export default HelloWorldFunctional;

Syntax of Class Component:

import React from 'react';

29
REACT JS

class App extends React.Component {

render() {

return (

<div>

<h1>Hello, World! (Class Component)</h1>

</div>

);

export default App;

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/>

import React from 'react';

import ReactDOM from 'react-dom';

import App from "./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 Equality Checking:

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:

In strict mode, you cannot delete variables.

"use strict";

var y = 5;
delete y; // Throws an error.

Duplicate Parameters:

In strict mode, you can't have duplicate function parameters.

"use strict";
function multiply(x, x) {
// Throws an error because of duplicate parameter names.
}

Octal Syntax:

31
REACT JS

Octal literals are not allowed in strict mode.

"use strict";
var num = 0123; // Throws an error as octal literals are not allowed.

This in Global Context:

this in the global context is {} in str ict mode.

"use strict";
console.log(this); // 'this' is {} in the global context.

Using "use strict"; in a Function: How this Behaves in Strict Mode":


"use strict";

function checkThis() {
console.log(this);
}

checkThis(); // Logs 'undefined' in strict mode.

Index.js:
import React from 'react';

import ReactDOM from 'react-dom';

import App from "./App";

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.

Functional Component With Arrow Function:

import React from 'react';

const App = () => {

return (

<>

<h1>Hello, I'm the App component!</h1>

</>

);

};

export default App;

In single line:

import React from 'react';

const App = () => <h1>Hello, I'm Single line App component!</h1>

export default App;

Combining Two Components using Functional Components :

Create Two Components in src ,here I have created ComponentOne and ComponentTwo

ComponentOne.jsx

import React from 'react'

const ComponentOne = () => {

return (

33
REACT JS

<div>

<h1>I am ComponentOne</h1>

</div>

export default ComponentOne

ComponentTwo.jsx

import React from 'react'

const ComponentTwo = () => {

return (

<div>

<h1>I am component two</h1>

</div>

export default ComponentTwo

App.jsx

import React from 'react';

import ComponentOne from './ComponentOne';

import ComponentTwo from './ComponentTwo';

const App = () => {

return (<>

<ComponentOne />

<ComponentTwo /></>)

export default App;

Here we are combining ComponentOne and ComponentTwo in App.jsx

34
REACT JS

Combining Two Components using Class Components :

Create Two Components in src ,here I have created ComponentOne and ComponentTwo

ComponentOne.jsx

import React from 'react'

class ComponentOne extends React.Component{

render(){

return(<>

<h1>Hello im ComponentOne</h1>

</>)

export default ComponentOne;

ComponentTwo.jsx

import React from 'react'

export default class ComponentTwo extends React.Component {

render() {

return (

<div>

<h1> Hello Hero I am Component Two</h1>

</div>

App.jsx

import React from 'react';

35
REACT JS

import ComponentOne from './ComponentOne';

import ComponentTwo from './ComponentTwo';

class App extends React.Component{

render(){

return(<> <ComponentOne/>

<ComponentTwo/>

</>)

export default App;

Here we are combining ComponentOne and ComponentTwo in App.jsx

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

Step 2:Now Write the Following Code in ExportImport.jsx

Default Export and import of single Element:

1)You can have one default export per module.

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

var message="Ameerpet Technologies";

export default message;

App.jsx

36
REACT JS

import React from 'react'

import message from './Components/ExportImport' //here instead of ‘message’ we can take any name as you like
see the following import hero

import hero from './Components/ExportImport'

export default function App() {

return (

<div>

<p>{message}</p>

<h1>{hero}</h1>

</div>

Muliple Elements Exporting and Importing

Example1:

ExportImport.jsx

var name="Ameerpet Technologies";

var fname="Hero";

var lname="Zero"

export default name;

export {fname,lname};

App.jsx

import React from 'react'

import message from './Components/ExportImport'

import {fname,lname} from "./Components/ExportImport"

export default function App() {

return (

37
REACT JS

<div>

<p>{message}</p>

<h1>{`${fname} ${lname}`}</h1> here we can write <h1>{fname}{lname}</h1> but we


know template literals

</div>

Example 2 :instead of writing import two times we can write in single line like following

import message,{fname,lname} from './Components/ExportImport'

ExportImport.jsx

Same code of the example1

App.jsx

import React from 'react'

import message,{fname,lname} from './Components/ExportImport'

export default function App() {

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;

export {sub,div,muul,}//here we are sending explicitly

export default add;// here we are sending defaultly sinle function

Here we can write the code in two ways as following you can use any process as for your requirement

Method1:

App.jsx

import React from 'react'

39
REACT JS

import add,{sub,div,muul} from './Components/ExportImport'

export default function App() {

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 React from 'react';

import add,{ sub, div, muul } from './Components/ExportImport'; // Import named exports without 'add'

export default function App() {

// Call the functions with arguments

const resultAdd = add(10, 5);

const resultSub = sub(10, 5);

const resultDiv = div(10, 5);

const resultMuul = muul(10, 5);

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.

Inside Components Folder Create MyReactModule.jsx

MyReactModule.jsx

import React from "react";

function Header(){

return(

41
REACT JS

<>

<h1>I am Header</h1>

</>

function IamBody(){

return(

<>

<h1>This is Body of the Page</h1>

</>

function Buttons(){

return(

<>

<button>Click Me</button>

</>

function Footer(){

return(

<>

<h1>I am Footer</h1>

</>

42
REACT JS

export default IamBody;

export {Header,Buttons,Footer}

App.jsx:

import React from 'react';

import IamBody,{Header,Buttons,Footer} from './Components/MyReactModule'

function App(){

return(

<>

<Header/>

<IamBody/>

<Buttons/>

<Footer/>

</>

export default App;

React Props:

props are short form for properties

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.

They are read-only, facilitating dynamic customization and component reuse.

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

import React from 'react'

const PropsExamples = (props) => {

return (

<div>

<h1>Hello {props.name}</h1>

</div>

export default PropsExamples

App.jsx

import React from 'react'

import PropsExamples from './Components/PropsExamples'

const App = () => {

return (

<div>

<PropsExamples name="Hero"/>

</div>

export default App

44
REACT JS

Example 2:

Sending Multiple Props to single Component

App.jsx

import React from 'react'

import PropsExamples from './Components/PropsExamples'

const App = () => {

return (

<div>

<PropsExamples fname="@vnvCoding" lname="_Technologies"/>

</div>

export default App

PropsExamples.jsx

import React from 'react'

const PropsExamples = (props) => {

return (

<div>

<h1>{`${props.fname} ${props.lname}`}</h1>

</div>

export default PropsExamples

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

import React from 'react'

const PropsExamples = (props) => {

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(

<>

<img src={props.imgurl} alt="randompics"/>

</>

export {ImageEx};

export default PropsExamples

App.jsx

import React from 'react'

import PropsExamples,{ImageEx} from './Components/PropsExamples'

const App = () => {

46
REACT JS

return (

<div>

<PropsExamples fname="@vnvCoding" lname="_Technologies"/>

<ImageEx imgurl="https://picsum.photos/200/300"/>

</div>

export default App

ReactDay-11
Passing Object as props in Parent Component (App.jsx)

App.jsx

import React from 'react'

import {Products} from './Components/PropsExamples'

const App = () => {

return (

<div>

<Products itemobj={{

name:"Laptop",

price:25000,

mfgyr:2023,

color:'black'

}}/>

</div>

47
REACT JS

export default App

Accessing The Object Props in Child Component Products inside PropsExample.jsx:

Write inside PropsExample.jsx below ImageEx component

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};

Passing Array As Props

App.jsx

import React from 'react'

import {ArrayProps} from './Components/PropsExamples'

const App = () => {

return (

<div>

<ArrayProps itemsarray={['laptop','mobile','washingmachine','watches']}/>

</div>

48
REACT JS

export default App

Accessing array props in Child Component ArrayProps in PropsExample.jsx using map method in using paragraph
tag

function ArrayProps(props) {

return (

<>

<h1>The Array Elements One by One</h1>

{props.itemsarray.map((value) => {

return (

<p>{value}</p>

})}

</>

);

export { Image, Products, ArrayProps };

export default PropsExamples

Accessing array props in Child Component ArrayProps in PropsExample.jsx using map method in Ordered Format
by using orderlist concept

function ArrayProps(props){

return (

<>

<h1>The Array Elements One by one</h1>

<ol>

{props.itemsarray.map((value,index)=>{

return (

<li key={index}>{value}</li>

49
REACT JS

})}

</ol>

</>

export {Image,Products,ArrayProps};

export default PropsExamples

Accessing array props in Child Component ArrayProps in PropsExample.jsx using map method in Tabular Format

function ArrayProps(props){

return (

<>

<h1>The Array Elements One by one</h1>

<table border='1' rules='all'>

<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};

export default PropsExamples

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) {

const listItems = [];

props.itemsarray.forEach((value, index) => {

listItems.push(<p key={index}>{value}</p>);

});

return (

<>

<h1>The Array Elements One by One</h1>

{listItems}

</>

);

51
REACT JS

export { Image, Products, ArrayProps };

export default PropsExamples

Passing Function as Props to Child Component

App.jsx

import React from 'react'

import {FunctionProps} from './Components/PropsExamples'

const App = () => {

return (

<div>

<FunctionProps message="Clickme" afterClicking={()=>{alert('clicked')}}/>

</div>

export default App

Childcomponent

function FunctionProps(props) {

return (

<>

<button onClick={props.afterClicking}>{props.message}</button>

</>

52
REACT JS

export { Image, Products, ArrayProps, FunctionProps };

export default PropsExamples

ReactDay-12
Props with Class Components:

Create a file(module) in Components Folder with the name:

App.jsx : sending ‘string’ as props to child component

import React from 'react'

import ClassProps from './Components/ClassProps';

const App = () => {

return (

<div>

<ClassProps title="Ameerpet Technologies" subtitle="For Inforamtion Technology"/>

</div>

export default App

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.

import React, { Component } from "react";

class ClassProps extends Component {

render() {

53
REACT JS

return (

<>

<h1>{`Title : ${this.props.title} ,Subtitle : ${this.props.subtitle}`}</h1>

</>

export default ClassProps;

Sending Image url in App.jsx

App.jsx

import React from 'react'

import {ImageClassProp} from './Components/ClassProps';

const App = () => {

return (

<div>

{/* /<ClassProps title="Ameerpet Technologies" subtitle="For Inforamtion Technology"/> */}

<ImageClassProp imgurl="https://picsum.photos/200/300"/>

</div>

export default App

create another component as ImageClassProp

class ImageClassProp extends Component {

render() {

54
REACT JS

return (

<>

<img src={this.props.imgurl} alt="randompic"/>

</>

export {ImageClassProp}

export default ClassProps;

Passing Function and Array As Prop in Class Component

import React from 'react'

import {FunctionProp,ArrayProp}from './Components/ClassProps';

const App = () => {

return (

<div>

<FunctionProp func={()=>9*10}/>

<ArrayProp arr={['1',2,4,6,9]}/>

</div>

export {FunctionProp,ArrayProp}

export default App

Accessing Function Props and Array Props in Class Component

class FunctionProp extends Component{

55
REACT JS

render(){

return(

<>

<h1>ans = {this.props.func()}</h1>

</>

class ArrayProp extends Component{

render(){

return(

<>

<ol>

{this.props.arr.map((value,index)=>{

return <li>{value}</li>

})}

</ol>

</>

export {ImageClassProp,FunctionProp,ArrayProp}

export default ClassProps;

Sending Object as Prop :

App.jsx

import React from 'react'

56
REACT JS

import {ObjProp}from './Components/ClassProps';

const App = () => {

return (

<div>

<ObjProp products={{

name:'hero',

age:28,

job:"software developer",

salary:'84lpa'

}}/>

</div>

export default App

Accesing object as prop in class Component

ObjProp.jsx

import React, { Component } from "react";

class ObjProp extends Component{

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}

export default ClassProps;

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.

 State is mutable, meaning it can be updated during the component's lifecycle.

Important Features of state in React Class 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.

Syntax for State in Class 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.

Create AllState.jsx file in Components Folder in src

AllState.jsx

import React, { Component } from 'react'

export default class AllState extends Component {

constructor(props){

super(props);

this.state={

data:25

render() {

return (

<div>

<p>{this.state.data}</p>

</div>

59
REACT JS

App.jsx

import React from 'react'

import AllState from './Components/AllState'

const App = () => {

return (

<div>

<AllState/>

</div>

export default App

Sending Props and Storing it has state:

App.jsx

import React from 'react'

import AllState from './Components/AllState'

const App = () => {

return (

<div>

<AllState fname="Hero" lname="Zero"/>

</div>

export default App

60
REACT JS

AllState.jsx

import React, { Component } from 'react'

export default class AllState extends Component {

constructor(props) {

super(props);

this.state = {

fname: props.fname,

lname: props.lname

render() {

const fullname = this.state.fname + this.state.lname

return (

<div>

<p>FirstName={this.state.fname}</p>

<p>LastName={this.state.lname}</p>

<h1>FullName={fullname}</h1>

</div>

Modification of the State:

App.jsx

61
REACT JS

import React from 'react'

import AllState from './Components/AllState'

const App = () => {

return (

<div>

<AllState fullname="Amp tech"/>

</div>

export default App

AllState.jsx

import React, { Component } from 'react

export default class AllState extends Component {

constructor(props) {

super(props);

this.state = {

name: "Hero",

zero: "Zero",

FullName: this.props.fullname

changeState = () => {

this.setState({ name: "zero", zero: "hero", FullName: "AMEERPET TECHNOLOGIES" })

render() {

62
REACT JS

return (

<div>

<button onClick={this.changeState}>ChangeTheState</button>

<h1>After State Change</h1>

<p>Hero:{this.state.name}</p>

<p>Zero:{this.state.zero}</p>

<p>FullName:{this.state.FullName}</p>

</div>

Count Program:

App.jsx

import React from 'react'

import AllState from './Components/AllState'

const App = () => {

return (

<div>

<AllState/>

</div>

export default App

63
REACT JS

AllState.jsx

import React, { Component } from 'react'

class AllState extends Component {

constructor(props) {

super(props);

this.state = {

count: 0

increaseCount = () => {

this.setState({ count: this.state.count + 1 })

render() {

return (

<>

<h1>Count:{this.state.count}</h1>

<button onClick={this.increaseCount}>increase</button>

<button onClick={() => { if (this.state.count > 0) { this.setState({ count: this.state.count - 1 }) }


}}>Decrease</button>

<button onClick={() => this.setState({ count: 0 })}>Reset</button>

</>

64
REACT JS

export default AllState

AnyProgram without using arrow function using:

App.jsx

Same code in above example

AllState.jsx

import React, { Component } from 'react';

class AllState extends Component {

constructor(props) {

super(props);

this.state = {

count: 0

};

// Explicitly binding the increaseCount method to the current component instance.

// This ensures that 'this' inside increaseCount refers to the component itself,

// allowing you to use 'this.setState' without issues.

this.increaseCount = this.increaseCount.bind(this);

// This method is used to update the 'count' in the component's state.

increaseCount() {

this.setState({ count: this.state.count + 1 });

render() {

return (

<>

<h1>Count: {this.state.count}</h1>

<button onClick={this.increaseCount}>Increase</button>

65
REACT JS

</>

);

export default AllState;

Difference of using variable and State in Class Component to store data:

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

import React, { Component } from 'react'

class AllState extends Component {

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

</>

export default AllState

Difference or Comparison Between Props and State

Aspect Props State


Immutable, cannot be changed Mutable, can be changed using
Mutability
in the component setState method
Passed from parent component Internally managed within the
Data Source
to child component component
Local to the component, not
Top-down (from parent to child
Data Flow designed for passing to other
components)
components
Set during component Initialized in the constructor and
Initialization
initialization and remains static can be updated over time
Available to read-only within Available for modification and
Scope
the component updates within the component
Typically used for configuring
Used for storing and managing
and customizing child
Use Cases component-specific data and
components based on parent
dynamic changes
components' data

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.

Proof or Example that Functional Component doesn’t handle State :

App.jsx:

import React from 'react'

import UseStateHook from './Components/UseStateHook'

const App = () => {

67
REACT JS

return (

<div>

<UseStateHook/>

</div>

export default App

Create UseStateHook.jsx in Components Folder of src

UseStateHook.jsx

import React from 'react'

export default function UseStateHook() {

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

1. Hooks were introduced in React version 16.8.

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.

list of some commonly used hooks in React:

1. useState: Allows you to add and manage state in functional components.


2. useEffect: Used for managing side-effects, such as data fetching or DOM manipulation.
3. useContext: Allows you to access the context within a functional component.
4. useRef: Creates a mutable ref object for accessing or holding references to elements or values.
5. useReducer: Provides a way to manage state through a reducer function, similar to Redux.
6. useCallback: Memoizes a callback function to prevent unnecessary re-renders.
7. useMemo: Memoizes a computed value to optimize performance.
8. useHistory and useLocation: Hooks from the react-router-dom library for working with
routing and navigation.
9. useNavigate: useNavigate is a function from React Router that allows for programmatic
navigation in a React application, enabling you to change routes without a full page reload.
10. useParams: A hook from react-router-dom for accessing URL parameters.

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.

Display state(here ex:name) using useState hook in Functional Component:

App.jsx

import React from 'react'

import UseStateHook from './Components/UseStateHook'

const App = () => {

return (

<div>

<UseStateHook/>

</div>

export default App;

UseStateHook.jsx

import React, { useState } from 'react'

export default function UseStateHook() {

const [name]=useState('Hero')

return (

70
REACT JS

<div>

<p>Name:{name}</p>

</div>

Change or Modify Name:

App.jsx

import React from 'react'

import UseStateHook from './Components/UseStateHook'

const App = () => {

return (

<div>

<UseStateHook/>

</div>

export default App;

UseStateHook.jsx

import React, { useState } from 'react'

export default function UseStateHook() {

const [name, setName] = useState('Hero')

const nameChange = () => {

setName( "Zero" );

return (

71
REACT JS

<div>

<p>Name:{name}</p>

<button onClick={nameChange }>ChangeName</button>

</div>

Count Increase

App.jsx

import React from 'react'

import UseStateHook from './Components/UseStateHook'

const App = () => {

return (

<div>

<UseStateHook/>

</div>

export default App;

UseStateHook.jsx

import React, { useState } from 'react'

export default function UseStateHook() {

const [count, setCount] = useState(0)

const increaseCount = () => {

setCount( count+1 );

return (

<div>

72
REACT JS

<p>Count:{count}</p>

<button onClick={increaseCount }>Increase</button>

</div>

Counter Component with using useState Hook and Props Concept ,Decrease(if count =0
then stop decreasing) and Reset Program

App.jsx:

import React from 'react'

import UseStateHook from './Components/UseStateHook'

const App = () => {

return (

<div>

<UseStateHook initialnumber={5}/>

</div>

UseStateHook.jsx:

import React, { useState } from 'react'

export default function UseStateHook(props) {

const [count, setCount] = useState(props.initialnumber)

const increaseCount = () => {

setCount( count+1 );

73
REACT JS

return (

<div>

<p>Count:{count}</p>

<button onClick={increaseCount }>Increase</button>

<button onClick={()=>{ if(count>0){setCount(count-1)}}}>Decrease</button>

<button onClick={()=>setCount(0)}>Reset</button>

</div>

ReactDay-15
JavaScript Concept:
JavaScript Events:

1. Definition: Events in JavaScript capture and respond to user, browser, or system


interactions on a web page.
2. Pattern:
o Event occurs.
o Triggers an event handler (JavaScript function).
o Event handler performs actions based on the event.

Common Event Types:

 User Events: Clicking, typing, mouse movement.


 Browser Events: Page load, resizing.
 System Events: Keyboard and mouse input.

Event Handling in JavaScript:

1. Inline Event Handlers:

74
REACT JS

o Define directly in HTML using attributes like onclick.


o Example: <button onclick="handleClick()">Click me</button>

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");

// Simulate a loading delay using setTimeout


setTimeout(() => {
afterLoading.innerHTML = "<h1>Page Reloaded</h1>";
}, 1000);
}

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:

o Modern and flexible approach.


o Attach event listeners using JavaScript code.

Click event: Example

<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:

var elementById = document.querySelector('#myId');

Select by Class:

var elementByClass = document.querySelector('.myClass');

Select by Tag Name:

var elementByTagName = document.querySelector('div');

Combining Selectors:

var combinedSelector = document.querySelector('div.myClass');

These examples show how to use querySelector to select elements by ID, class, tag name, and a combination of
these selectors.

77
REACT JS

Difference Between querySelector and getElementById

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

<meta name="viewport" content="width=device-width, initial-scale=1.0">


<title>Document</title>
</head>

<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>

Difference between Window and Document:

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).

Difference Between EventHandlers and EventListeners


Aspect Event Handler Event Listener
 Registration  Inline HTML attributes  JavaScript methods
Method (onclick, onmouseover) (addEventListener)
 Number of  One handler per event  Multiple listeners can be
Handlers type per element added for the same event
 Limited flexibility and can  More flexible; multiple
 Flexibility
be overwritten listeners can coexist
 Overwriting  Subsequent handlers  Multiple listeners do not
Handlers overwrite previous ones overwrite each other

79
REACT JS

Aspect Event Handler Event Listener


 Access to Event  Implicit access (event is  Explicit access (event is a
Object available directly) parameter in the callback)
 Defined in HTML attribute  Defined using JavaScript
 Target Element
(e.g., onclick="...") (addEventListener)
 Preferred for better
 Generally considered less
 Best Practice structure and
maintainable
maintainability

Event Object:

 Important in event handling, automatically passed to event handler function.


 Provides information about the event, e.g. event type, target element.

function handleClick(event) {
alert("Event type: " + event.type);
alert("Target element: " + event.target);
// Other event properties
}

Common Event Object Properties:

 type: Type of the event (e.g., "click," "keydown").


 target: Element that triggered the event.
 clientX and clientY: Mouse cursor coordinates for mouse events.
 key: Key pressed for keyboard events.
 value: Value of an input element for input events.

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.

Common Properties of Event Object:

type: A string indicating the type of event (e.g., "click", "keydown").

target: The DOM element that triggered the event.

currentTarget: The element whose event listener is currently being processed.

eventPhase: The phase of the event flow (capturing, at target, or bubbling).

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

<meta name="viewport" content="width=device-width, initial-scale=1.0">


<title>Document</title>
</head>

<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:

 const inputValue = event.target.value;

 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:

 const elementTagName = event.target.tagName;

 id:

 Usage: event.target.id
 Description: Returns the id attribute of the element.
 Example:

 const elementId = event.target.id;

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:

 const attributeValue = event.target.getAttribute('data-custom');

 parentNode:

 Usage: event.target.parentNode
 Description: Returns the parent node of the element.
 Example

const parentElement = event.target.parentNode;

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");

myButton.addEventListener('click', function (event) {

ouroutput.innerHTML = 'Event Target: ' +event.target.tagName;


});
</script>
</body>

84
REACT JS

</html>

Not Event Related Normal Form and Displaying details in Console:

<!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

A TextBox ,where what ever You write will Print in Console

Example1: By using document.getElementById()

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

event.preventDefault(); // Prevent default form submission behavior


});
</script>
</body>

</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.

If you Remove event.preventDefault() in anymethod the page will be automatically refereshed


so you will loss the data. so that you cannot show the data in console

Form Submission with Class Component:


App.jsx:

import React from 'react'


import ReactEvents from './HooksTotal/ReactEvents'

export default function App() {


return (
<div>
<ReactEvents/>
</div>
)
}

ReactEvents.jsx

import React, { Component } from 'react';


class ReactEvents extends Component {
constructor(props) {
super(props);
this.state = {
name: " ",

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.

Form Submission With Functional Component using useState:

App.jsx

88
REACT JS

import React from 'react'


import ReactEvents from './HooksTotal/ReactEvents'

export default function App() {


return (
<div>
<ReactEvents/>
</div>
)
}

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}>

<label >Name:</label><input type="text" value={name} onChange={handleName} />


<label >Email:</label><input type="text" value={email} onChange={handleEmail} />

<input type="submit" value="Submit Properly" />


</form>
</>
)

89
REACT JS

}
export default ReactEvents;

ReactDay-18
Life Cycle Methods: Life cycle methods also called as SideEffects because it acts
based on actions

LifeCycle Methods (side Effects)in Class-Components:

Its is a process of executing the methods

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

Side effects in functional component is useEffect  functional based component

LifeCycleMethods:

1)ComponentDidMount(): only once , it executes very first time(immediate action of render) ,


relatime: api calls or data getting or fetching

2)componentDidUpdate():it triggers when any state value is changed,realtime :when we add


item to cart the cart will be updated so it will trigger componentDidUpdate()

3)ComponentWillUnmount(): right before removing component

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()

o Invoked when creating a new component instance.


o Responsible for initializing state and binding event handlers.

class MyComponent extends React.Component {


constructor(props) {
super(props);
this.state = {
// initialize state
};
// bind event handlers
}
}

Mounting:

render()

o Renders the component's UI.


o Should be a pure function without side effects.

jsx
class MyComponent extends React.Component {
render() {
return (
// JSX representing component UI
);
}
}

componentDidMount()

o Called after the component is rendered.

91
REACT JS

o Ideal for initiating network requests or updating the DOM.

class MyComponent extends React.Component {


componentDidMount() {
// perform post-render operations
}
}

Updating:

shouldComponentUpdate(nextProps, nextState)

o Decides whether the component should re-render.


o Optimizes performance by preventing unnecessary renders.

class MyComponent extends React.Component {


shouldComponentUpdate(nextProps, nextState) {
// return true or false based on conditions
}
}

componentDidUpdate(prevProps, prevState)

o Called after the component is updated.


o Useful for side effects like network requests based on changes.

class MyComponent extends React.Component {


componentDidUpdate(prevProps, prevState) {
// perform actions based on prop or state changes
}
}

Unmounting:

 componentWillUnmount()
o Invoked before a component is unmounted and destroyed.
o Used for cleanup operations.

class MyComponent extends React.Component {


componentWillUnmount() {
// perform cleanup tasks before component is destroyed
}
}

Error Handling:

 componentDidCatch(error, info)

92
REACT JS

o Catches JavaScript errors in the component tree.


o Useful for displaying fallback UI and logging errors.

class ErrorBoundary extends React.Component {


componentDidCatch(error, info) {
// handle errors gracefully
}

render() {
return this.props.children;
}
}

import React, { Component } from 'react';

class LifeCycleMethods extends Component {


constructor(props) {
super(props);
this.state = {
message: 'Hello, World!',
};
console.log('Constructor called');
}

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>
);
}
}

export default LifeCycleMethods;*/

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

 Logical NOT (!):

 let isTrue = true;


let isFalse = !isTrue; // Logical NOT operator, isFalse is now false

 Typeof Operator:

let variable = "Hello";


let type = typeof variable; // Typeof operator, type is now "string"

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 (/):

1. let numerator = 20;


2. let denominator = 4;
3. let quotient = numerator / denominator; // Binary division operator, quotient is 5

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:

Maximum of Two Numbers:

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

 Check Even or Odd:

let num = 10;


let parity = (num % 2 === 0) ? "Even" : "Odd"; // Ternary conditional operator, parity is assigned
"Even" or "Odd"

 Assign Value Based on Condition:

let isSunny = true;


let activity = isSunny ? "Go to the beach" : "Go to the movies"; // Ternary conditional operator,
activity depends on weather

 Check Null or Assign Default:

let name = null;


let result = name ?? "Default Name"; // Nullish coalescing operator, result is "Default Name" if
name is null

 Assign Value Based on Multiple Conditions:

let hour = 15;


let greeting = (hour < 12) ? "Good morning" : (hour < 18) ? "Good afternoon" : "Good
evening";
// Nested ternary operators, greeting depends on the time of day

componentWillUnmount():

It will be called just before a component is about to be unmounted or removed from the DOM.

App.jsx

import React, { Component } from 'react'


import LifeCycleMethods from './HooksTotal/LifeCycleMethods'

export default class App extends Component {


render() {
return (
<div>
<LifeCycleMethods />
</div>
)

96
REACT JS

}
}

LifeCycleMethods.jsx

import React, { Component } from 'react'


import LifeCycleMethodTwo from './LifeCycleMethodTwo';

export default class LifeCycleMethods extends Component {


constructor() {
super();
this.state = {
show: false
}
}
render() {
return (
<div>
{this.state.show ? <LifeCycleMethodTwo /> : null}

<button onClick={() => this.setState({ show:!this.state.show })}>Hide and SHOW</button>


</div>
)
}
}

LifeCycleMethodTwo.jsx

import React, { Component } from 'react'

export default class LifeCycleMethodTwo extends Component {


componentWillUnmount(){
console.log("componentWillUnmount is Called");
}
render() {
return (
<div>

Hello Here Component Will Be deleted and Added


</div>
)
}
}

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.

The useEffect hook takes two arguments:

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:

import React from 'react'


import UseEffectExamples from './HooksTotal/UseEffectExamples'

export default function App() {


return (
<div>
<UseEffectExamples/>
</div>
)
}

UseEffectExamples.jsx :useEffect without dependency Array

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.

import React, { useEffect, useState } from 'react'

export default function UseEffectExamples() {


const[count,setCount]=useState(0);
useEffect(()=>{
alert("Always render")
console.log(" Always Render")

})
return (
<div>
<h1>Count:{count}</h1>
<button onClick={()=>{setCount(count+1)}}>Increase</button>
</div>
)
}

Using An Empty Dependency Array: here it acts as componentDidMount():

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.

import React, { useEffect, useState } from 'react'

export default function UseEffectExamples() {


const[count,setCount]=useState(0);
useEffect(()=>{
alert("Always render")
console.log(" Always Render")

},[])
return (
<div>
<h1>Count:{count}</h1>
<button onClick={()=>{setCount(count+1)}}>Increase</button>
</div>
)
}

ReactDay-20
useEffect :

Example:to change the title of document by using useEffect

UseEffectExamples.jsx

import React, { useState, useEffect } from 'react';


function UseEffectExamples() {
const [count, setCount] = useState(0);

// Similar to componentDidMount and componentDidUpdate:


useEffect(() => {
// Update the document title using the browser API
document.title = count;
}
)
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>

100
REACT JS

Click me
</button>
</div>
);
}
export default UseEffectExamples;

Example-2:

import React, { useEffect, useState } from 'react'

export default function UseEffectExamples(props) {


const[num1,setNum1]=useState(0);
useEffect(()=>{
alert("Hello");

})
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

import React, { useEffect, useState } from 'react'

export default function UseEffectExamples() {


const[num1,setNum1]=useState(0);
useEffect(()=>{
alert("Hello");
},[num1])

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

import React, { useEffect, useState } from 'react'

export default function UseEffectExamples(props) {


const[num1,setNum1]=useState(0);

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>
)
}

Example : useState with array and adding elements to array

import React, { useState } from 'react';

const UseEffectExamples = () => {


const [numbers, setNumbers] = useState([1, 2, 3]);

return (
<>
<ol>
{numbers.map((cv, i) => (
<li key={i}>{cv}</li>
))}
</ol>
<button onClick={() => setNumbers([...numbers, numbers.length + 1])}>change</button>
</>
);
}

export default UseEffectExamples;

Example: useEffect

import React, { useEffect, useState } from 'react';


const UseEffectExamples = () => {
const [numbers, setNumbers] = useState([1, 2, 3]);

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>
</>
);
}

export default UseEffectExamples;

Example:

import React, { useEffect, useState } from 'react';


const UseEffectExamples = () => {
const [person, setPerson] = useState({ name: "Hero", age: 21 });
useEffect(() => {
alert(`name changed to : ${person.name}`);
}, [person.name])

return (
<>
<p>{person.name}</p>
<p>{person.age}</p>
<button onClick={() => {

setPerson({ ...person,name:"Zero" })
}}>Change Name</button>
</>
);
}

export default UseEffectExamples;

Example:

104
REACT JS

import React, { useEffect, useState } from 'react';


const UseEffectExamples = () => {
const [person, setPerson] = useState({ name: "Hero", age: 21 });
useEffect(() => {
alert(`name changed to : ${person.name}`);
}, [person.name])
const handleName = () => {
const newName=person.name==="Hero"? "Zero":"Hero"
setPerson({ ...person, name: newName })
}
return (
<>
<p>{person.name}</p>
<p>{person.age}</p>
<button onClick={handleName }>Change Name</button>
</>
);
}

export default UseEffectExamples;

ReactDay-21
App.jsx

import React from 'react'


import UseReducerHookEx from './HooksTotal/UseReducerHookEx'

export default function App() {


return (
<div>
<UseReducerHookEx/>
</div>
)
}

Create UseReducerHookEx in HooksTotal


UseReducerHookEx.jsx useState ex

105
REACT JS

import React, { useState } from 'react'

export default function UseReducerHookEx() {


const [num1, setNum1] = useState(0)
const [num2, setNum2] = useState(100)
const [num3, setNum3] = useState(1)
const [num4, setNum4] = useState(100)
return (
<div>
<>
<p>{`Add:${num1} Substract:${num2} Multiply:${num3} Division:${num4}`}</p>
<button onClick={() => setNum1(num1 + 1)}>Increase</button>
<button onClick={() => setNum2(num2 - 1)}>Decrease</button>
<button onClick={() => setNum3(num3 * 2)}>Multiply</button>
<button onClick={() => setNum4(num4 / 2)}>Division</button>
</>
</div>
)
}

UseReducerHookEx.jsx

useReducer:

Definition: A reducer function is a JavaScript function that takes two arguments: the current
state and an action.

Syntax: The syntax typically looks like this:

const reducer = (state, action) => {

// Logic to handle state changes based on action type

};

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

const [state, dispatch] = useReducer(reducer, initialArg);

state: The current state value.

dispatch: A function used to dispatch actions to update the state.

reducer: A function that specifies how state transitions occur based on dispatched actions.

initialArg: The initial state value or an optional lazy initialization function.

UseReducerHookEx.jsx

import React, { useReducer } from 'react'


export default function UseReducerHookEx() {
const reducer=(cs,action)=>{
if(action.type==="Increment"){
return cs +1;
}
else if(action.type==="Decrement"){
return cs-1;
}
else if(action.type==="Multiply"){
return cs*2;
}
else if(action.type==="Division"){
return cs/2;
}n
}
const[state,dispatch]=useReducer(reducer,0);
return (
<div>
<p>{state}</p>
<button onClick={()=>dispatch({type:"Increment"})}>Increase</button>
<button onClick={()=>dispatch({type:"Decrement"})}>Decrease</button>
<button onClick={()=>dispatch({type:"Multiply"})}>Multiply</button>
<button onClick={()=>dispatch({type:"Division"})}>Division</button>
</div>
)
}

UseReducerHookEx.jsx

107
REACT JS

Taking initialstate as object and modifying the values

import React, { useReducer } from 'react'


const reducer = (currentstate, action) => {
if(action.type==="increase"){
return {...currentstate,count:currentstate.count+1}
}
else if(action.type==="decrease"){
return {...currentstate,count:currentstate.count-1}
}
else if(action.type==="nameChange"){
return{...currentstate,name: currentstate.name==="Hero"?"zero":"Hero"
}
}

}
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>
)
}

Developing Form Using useState:

import React, { useState } from 'react'

export default function UseReducerHookEx() {


const [name, setName] = useState("");
const [pswrd, setPass] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
alert(name+""+pswrd)

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>
)
}

Creating a Form Using useRedcer:

UseReducerHookEx.jsx

import React, { useReducer } from 'react'

export default funct ion UseReducerHookEx() {


const reducer = (cs, action) => {
if (action.type === "nameChange") {
return { ...cs, name: action.value }
}
else if (action.type === "pswrdChange") {
return { ...cs, pswrd: action.value }
}

}
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'

export default function App() {


return (
<div>
<UseRefHook/>
</div>
)
}

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 .

So ,here its creates a infinite loop of rendering of component

import React, { useEffect, useState } from 'react'

export default function UseRefHook() {


const [count, setCount] = useState(0);
const[data,setMyData]=useState("");
useEffect(() => {
setCount(count+1);
console.log(data)

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:

It creates a mutable variable which will not re-render the component

useRef hook returns a object named as Current

UseRefHook.jsx

The Above problem can be solved here by using useRef hook

import React, { useEffect, useState ,useRef} from 'react'

export default function UseRefHook() {


//const [count, setCount] = useState(0);
const[data,setMyData]=useState("");
const count=useRef(0);
console.log(count)
useEffect(() => {
//setCount(count+1);
count.current=count.current+1;

})
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:

it is used to access the DOM directly

UseRefHook.jsx

To see total refenced field of DOM

import React, { useState ,useRef} from 'react'

export default function UseRefHook() {


//const [count, setCount] = useState(0);
const[data,setMyData]=useState("");
const input=useRef(0);

const changeStyle=()=>{
console.log(input)
console.log(input.current)

return (
<div>

<input ref={input} type="text" onChange={(e) =>setMyData(e.target.value)} value={data}/>


<button onClick={changeStyle}>ChangeStyle</button>
</div> 4
)
}

Example:

Manipulating DOM using useRef hook

import React, { useState ,useRef} from 'react'

export default function UseRefHook() {

const[data,setMyData]=useState("");
const input=useRef(0);

const changeStyle=()=>{

112
REACT JS

input.current.style.backgroundColor="Red";
input.current.focus();

return (
<div>

<input ref={input} type="text" onChange={(e) =>setMyData(e.target.value)} value={data}/>


<button onClick={changeStyle}>ChangeStyle</button>
</div>
)
}

Prop Drilling Concept:

 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

import React from 'react'


import CompA from './HooksTotal/CompA'

export default function App() {


return (
<div>
<CompA name="Hero"/>
</div>
)
}

CompA.jsx

import React from 'react'


import CompB from './CompB'

113
REACT JS

export default function CompA(props) {


return (
<div>
<CompB name={props.name}/>
</div>
)
}

CompB.jsx

import React from 'react'


import CompC from './CompC'
export default function CompB(props) {
return (
<div>
<CompC name={props.name}/>
</div>
)
}

CompC.jsx

import React from 'react'


import CompD from './CompD'
export default function CompC(props) {
return (
<div>
<CompD name={props.name}/>
</div>
)
}

CompD.jsx

import React from 'react'

export default function CompD(props) {


return (
<div>
<h1>Hero Im Component D {props.name}</h1>
</div>
)
}

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.

Here are the key concepts related to the Context API:

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

<MyContext.Provider value={/* some value */}>


{/* Components within this Provider have access to the context value */}
<SomeComponent />
</MyContext.Provider>

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>

Example1: to send single data in single createContext


App.jsx

Here we will create a Context and Provider

 here we have to use value to send data not anything other than this

import React, { createContext } from 'react'


import CompA from './HooksTotal/CompA'
const Fname = createContext();
function App() {
return (
<div>
<Fname.Provider value={"Hero Pullayya"}>
<CompA />
</Fname.Provider>
</div>
)
}
export default App;
export {Fname};

CompA.jsx

import React from 'react'


import CompB from './CompB'

export default function CompA() {


return (
<div>
<CompB />
</div>
)

116
REACT JS

CompB.jsx

import React from 'react'


import CompC from './CompC'
export default function CompB() {
return (
<div>
<CompC />
</div>
)
}

CompC.jsx

import React from "react";


import CompD from "./CompD";
export default function CompC() {
return (
<>
<CompD />
</>
);
}

CompD.jsx

This is the file(grand Child Component) where I want to consume or use the data

import React from 'react'


import { Fname } from '../App'
export default function CompD() {
return (
<div>
<Fname.Consumer>
{(fname)=>{
return(
<h1>Hello {fname}</h1>
)

117
REACT JS

}}
</Fname.Consumer>
</div>
)
}

Example 2:
To send Object in single createContext:

App.jsx

Here we will Create a Context and Provider and pass Object

import React, { createContext } from "react";


import CompA from "./HooksTotal/CompA";
const Fname = createContext();
function App() {
return (
<div>
<Fname.Provider value={{fname:"Hero",lname:"Zero"}}>
<CompA />
</Fname.Provider>
</div>
);
}
export default App;
export { Fname };

CompD.jsx

Here we will Consume or use the Data

import React from 'react'


import { Fname } from '../App'
export default function CompD() {
return (
<div>
<Fname.Consumer>
{(person)=>{

118
REACT JS

return(
<h1>Hello {`FirstName = ${person.fname} and LastName = ${person.lname}`}</h1>
)
}}
</Fname.Consumer>
</div>
)
}

Example3:

Creating 2 createContexts and sending data

App.jsx

import React, { createContext } from "react";


import CompA from "./HooksTotal/CompA";
const Fname = createContext();
const Lname=createContext();
function App() {
return (
<div>
<Fname.Provider value={"Hero"}>
<Lname.Provider value={"Zero"}>
<CompA />
</Lname.Provider>
</Fname.Provider>
</div>
);
}
export default App;
export { Fname ,Lname};

CompD.jsx

Receiving data or Consuming the data

import React from 'react'


import { Fname,Lname } from '../App'
export default function CompD() {
return (
<div>

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:

Using another Component also with ContextApi:

App.jsx

import React, { createContext } from "react";


import CompA from "./HooksTotal/CompA";
const Fname = createContext();
const Lname=createContext();
function App() {
return (
<div>
<Fname.Provider value={"Hero"}>
<Lname.Provider value={"Zero"}>
<CompA />
</Lname.Provider>
</Fname.Provider>
</div>
);
}
export default App;
export { Fname ,Lname};

CompC.jsx

120
REACT JS

This are the places or areas where you can use another Component also

here I use CompD {another Component}

import React from "react";


import CompD from "./CompD";
import { Fname, Lname } from "../App";
export default function CompC() {
return (
<>
<CompD />
<Fname.Consumer>
{(fname) => {
return (
<Lname.Consumer>
{(lname) => {
return (
<h1>
{` This line is Main file ,Hello my firstname is ${fname} and my lastname is ${lname}`}
<CompD />
</h1>
);
}}
</Lname.Consumer>
);
}}
</Fname.Consumer>
<CompD/>
</>
);
}

CompD.jsx

import React from "react";

export default function CompD(props) {


return (
<div>
<h1>This is CompD =this are the places you can use another Component while using Consumer</h1>
</div>
);
}

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.

Here's a brief explanation of how useContext works:

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

// Example of creating a context

const MyContext = React.createContext();

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

<MyContext.Provider value={/* your value */}>


{/* Your component tree */}
</MyContext.Provider>

3) Consuming the Context: Now, in any child component, you can use the useContext hook to access the value
provided by the context.

jsx

// Example of consuming the context

import React, { useContext } from 'react';

function MyComponent() {
const contextValue = useContext(MyContext);

// Now, contextValue has the value provided by the context


// Do something with the context value
}

122
REACT JS

The useContext hook takes the context object as its argument and returns the current context value.

App.jsx

import React, { createContext } from "react";


import CompA from "./HooksTotal/CompA";
const Fname = createContext();
const Lname=createContext();
function App() {
return (
<div>
<Fname.Provider value={"Zero"}>
<Lname.Provider value={"Hero"}>
<CompA />
</Lname.Provider>
</Fname.Provider>
</div>
);
}
export default App;
export { Fname ,Lname};

CompA.jsx

import React from 'react'


import CompB from './CompB'

export default function CompA() {


return (
<div>
<CompB />
</div>
)
}

CompB.jsx

import React from 'react'


import CompC from './CompC'
export default function CompB() {
return (
<div>
<CompC />

123
REACT JS

</div>
)
}

CompC.jsx

import React from "react";


import CompD from "./CompD";

export default function CompC() {


return (
<>
<CompD />
</>
);
}

CompD.jsx

import React, { useContext } from "react";


import { Fname, Lname } from "../App";
export default function CompD(props) {
const fname = useContext(Fname);
const lname = useContext(Lname);
return (
<>
<h1>
{`Hello my name is ${fname} and i can
become ${lname}`}
</h1>
</>
);
}

Example: passing object and Array

App.jsx

124
REACT JS

import React, { createContext } from "react";


import CompA from "./HooksTotal/CompA";
const Person= createContext();
const NamesList=createContext();
function App() {
return (
<div>
<Person.Provider value={{name:"Hero",age:"21",address:"Hyderabad"}}>
<NamesList.Provider value={["Lokesh","Ajay","Govardhan","Sonal","Malleshwari"]}>
<CompA />
</NamesList.Provider>
</Person.Provider>
</div>
);
}
export default App;
export { Person ,NamesList};

CompD.jsx

accessing object and array using useContext

used inline css

import React, { useContext } from "react";


import { Person, NamesList } from "../App";
export default function CompD() {
const person = useContext(Person);
const namesarray = useContext(NamesList);
return (
<>
<h1 style={{ color: "red" }}>My details are</h1>
<ol>
<h1>
<li>name:{person.name}</li>
<li>age:{person.age}</li>
<li>address:{person.address}</li>
</h1>
</ol>
<h1>
<span style={{ backgroundColor: "green" }}>My Friends are</span>
</h1>
<ol>
{namesarray.map((cv) => {

125
REACT JS

return <li key={cv.id}>{cv}</li>;


})}
</ol>
</>
);
}

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.

Key components of the World Wide Web:

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.

Example URL: https://www.example.com:8080/path/to/resource?param=value#section

In this example, "https" is the scheme,

126
REACT JS

"www.example.com" is the host,

":8080" is the port (optional),

"/path/to/resource" is the path,

"?param=value" are query parameters, and "#section" is the fragment.

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:

react-router-dom is a popular library for implementing routing in React applications.

It provides a way to navigate between different components or pages in a React application without triggering a full
page reload.

BrowserRouter: to connect our app to browser’s url

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 and NavLink:

 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:

First install react-router-dom in your project

Command:

npm install react-router-dom@6

Example1: this will show at Url http://localhost:3000

App.jsx

import React from "react";


import { BrowserRouter, Route,Routes} from "react-router-dom";

export default function App() {


return (
<BrowserRouter>
<Routes>
<Route path="/" element={<h1>Hello</h1>} />

</Routes>
</BrowserRouter>
);
}

128
REACT JS

Example2: this will show at url http://localhost:3000/about

App.jsx

import React from "react";


import { BrowserRouter, Route, Routes } from "react-router-dom";

export default function App() {


return (
<BrowserRouter>
<>
<Routes>
<Route path="/" element={<h1>Hero</h1>} />
<Route path="/about" element={<>about Page</>}/>
</Routes>
</>
</BrowserRouter>
);
}

Step1Now create RouterConcepts Folder in AllHooks Folder

Step2 inside RouterConcepts Folder create

1. Home.jsx
2. About.jsx
3. Contact.jsx

Home.jsx

import React from 'react'

const Home = () => {


return (
<div>
<h1>This is Home Page</h1>
</div>
)
}

export default Home

129
REACT JS

About.jsx

import React from "react";

const About = () => {


return (
<div>
<h1>This is About Page</h1>
</div>
);
};

export default About;

Contact.jsx

import React from 'react'

const Contact = () => {


return (
<div>
<h1>This is Contact Page</h1>
</div>
)
}

export default Contact

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

Import every component and pass it in element of Route

import React from "react";


import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "./HooksTotal/RouterConcept/Home";
import About from "./HooksTotal/RouterConcept/About";
import Contact from "./HooksTotal/RouterConcept/Contact";

export default function App() {


return (
<BrowserRouter>
<>
<Routes>
<Route path="/" element={<Home/>} />
<Route path="/about" element={<About/>}/>
<Route path="/contact" element={<Contact/>}/>
</Routes>
</>
</BrowserRouter>
);
}

Example:

Using ‘Link’ : in react ‘Link’ works as anchor tag ,’to’ works as href

Beside ‘to’ give the same ‘name’ as given in ‘’route’s path’’

import { Link } from 'react-router-dom'

create LinksComp.jsx in RoutesConcept Folder

LinksComp.jsx

import React from "react";


import { Link } from "react-router-dom";

const LinksComp = () => {


return (
<>
<nav>
<li>

131
REACT JS

<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</nav>
</>
);
};

export default LinksComp;

Then import LinksComp.jsx in every component where it is required

Here I imported and used ‘LinksComp’ in Home.jsx,About.jsx,Contact.jsx

import React from "react";


import LinksComp from "./LinksComp";

const Home = () => {


return (
<div>
<LinksComp />
<h1>Home Page</h1>
</div>
);
};

export default Home;

NavLink:

To Know the active or current Page we will use NavLink Component

It works Similar to Link ,but it provides extra feature ‘active class’

132
REACT JS

By using active class lets add css to it

LinksComp.jsx

Just Replace the Link with NavLink

import React from "react";


import { NavLink } from "react-router-dom";

const LinksComp = () => {


return (
<>
<nav>
<li>

<NavLink to="/" >Home</NavLink>


</li>
<li>
<NavLink to="/about">About</NavLink>
</li>
<li>
<NavLink to="/contact">Contact</NavLink>
</li>
</nav>
</>
);
};

export default LinksComp;

App.css

.active{
color:red;
background-color:yellow;
}

App.jsx

//Don’t Forget to import App.css

133
REACT JS

import React from "react";


import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "./HooksTotal/RouterConcept/Home";
import About from "./HooksTotal/RouterConcept/About";
import Contact from "./HooksTotal/RouterConcept/Contact";
import './App.css'
export default function App() {
return (
<BrowserRouter>
<>
<Routes>
<Route exact path="/" element={<Home/>} />
<Route path="/about" element={<About/>}/>
<Route path="/contact" element={<Contact/>}/>
</Routes>
</>
</BrowserRouter>
);
}

ReactDay-26
If page Doesn’t exist ,it should show following message

404 page Not found….

Method 1:
Home.jsx

import React from "react";

const Home = () => {


return <div>Home Page</div>;
};

export default Home;

About.jsx

import React from "react";

134
REACT JS

const About = () => {


return (
<div>
<h1>This is About Page</h1>
</div>
);
};

export default About;

Contact.jsx

import React from "react";

const Contact = () => {


return (
<>

<h1>This is Contact Page</h1>


</>
);
};

export default Contact;

LinksComp.jsx
import React from "react";
import { NavLink } from "react-router-dom";

const LinksComp = () => {


return (
<>
<nav>
<li>

<NavLink to="/" >Home</NavLink>


</li>
<li>
<NavLink to="/about">About</NavLink>
</li>

135
REACT JS

<li>
<NavLink to="/contact">Contact</NavLink>
</li>
</nav>
</>
);
};

export default LinksComp;

App.jsx

import React from "react";


import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "./HooksTotal/RouterConcept/Home";
import About from "./HooksTotal/RouterConcept/About";
import Contact from "./HooksTotal/RouterConcept/Contact";
import "./App.css";
import LinksComp from "./HooksTotal/RouterConcept/LinksComp";
export default function App() {
return (
<BrowserRouter>
<LinksComp />
<Routes>
<Route exact path="/" element={<Home />}></Route>
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="*" element={<h1>404 Page Not Found...</h1>} />

</Routes>
</BrowserRouter>
);
}

This is the only extra line we added to our previous day example

<Route path="*" element={<h1>404 Page Not Found...</h1>} />

Extra Topic

136
REACT JS

You can get emojis from various sources. Here are a few options:

1. Emoji Keyboard on your device:


o On most devices, there's an emoji keyboard that you can access. For example, on
Windows, you can use the "Win + ." shortcut, and on macOS, you can use "Ctrl +
Cmd + Space" to open the emoji keyboard.
2. Emoji Websites:
o Websites like Emojipedia provide a comprehensive list of emojis. You can search
for emojis and copy them directly from the website.
3. Character Map (Windows) or Character Viewer (Mac):
o On Windows, you can use the Character Map to find and copy emojis. On Mac,
you can use the Character Viewer.

Method 2:

Create Error Component:

ErrorComp.jsx

import React, { useEffect } from "react";

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>
);
}

export default ErrorComp;


To add Emoji

137
REACT JS

App.jsx

Here import and Pass That Component into Route Path

import React from "react";


import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "./HooksTotal/RouterConcept/Home";
import About from "./HooksTotal/RouterConcept/About";
import Contact from "./HooksTotal/RouterConcept/Contact";
import "./App.css";
import LinksComp from "./HooksTotal/RouterConcept/LinksComp";
import ErrorComp from "./HooksTotal/RouterConcept/ErrorComp";
export default function App() {
return (
<BrowserRouter>
<LinksComp />
<Routes>
<Route exact path="/" element={<Home />}></Route>
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="*" element={<ErrorComp/>} />

</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.

import React from "react";


import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "./HooksTotal/RouterConcept/Home";
import About from "./HooksTotal/RouterConcept/About";
import Contact from "./HooksTotal/RouterConcept/Contact";
import "./App.css";
import LinksComp from "./HooksTotal/RouterConcept/LinksComp";
import ErrorComp from "./HooksTotal/RouterConcept/ErrorComp";
export default function App() {
return (
<BrowserRouter>
<LinksComp />

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

Home.jsx: now Home component will work as NavBar

import React from "react";


import { Outlet } from "react-router-dom";

const Home = () => {


return (
<div>
<Outlet />
</div>
);
};

export default Home;

useNavigate():used to programmatically navigate between different pages or views.

Without Using Link tag We can Navigate through different Pages

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

import React from "react";


import { useNavigate } from "react-router-dom";

const Home = () => {

139
REACT JS

const navigate = useNavigate();

return (
<div>
<h1>Home Page</h1>
<button onClick={() => navigate("/about")}>About</button>
<button onClick={() => navigate("/contact")}>Contact</button>

</div>
);
};

export default Home;

Contact.jsx

import React from "react";


import { useNavigate } from "react-router-dom";

const Contact = () => {


const navigate=useNavigate();
return (
<>

<h1>This is Contact Page</h1>


<button onClick={() => navigate("/about")}>About</button>
<button onClick={() => navigate("/")}>Home</button>

</>
);
};

export default Contact;

About.jsx

import React from "react";


import { useNavigate } from "react-router-dom";

140
REACT JS

const About = () => {


const navigate=useNavigate();
return (
<>

<h1>This is About Page</h1>


<button onClick={() => navigate("/contact")}>Contact</button>
<button onClick={() => navigate("/")}>Home</button>

</>
);
};

export default About;

App.jsx

Here I removed LinksComp to avoid the usage of ‘Link’ of ‘’react-router-dom’’

import React from "react";


import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "./HooksTotal/RouterConcept/Home";
import About from "./HooksTotal/RouterConcept/About";
import Contact from "./HooksTotal/RouterConcept/Contact";
import "./App.css";
//import LinksComp from "./HooksTotal/RouterConcept/LinksComp";
import ErrorComp from "./HooksTotal/RouterConcept/ErrorComp";
export default function App() {
return (
<BrowserRouter>
{/* <LinksComp /> */}
<Routes>
<Route exact path="/" element={<Home />}></Route>
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="*" element={<ErrorComp/>} />

</Routes>
</BrowserRouter>
);
}

141
REACT JS

ReactDay-27
To access Query Params in Url

Or to access sub page or sub data of the Page

We Use useParams Hook

But Let us See How We (The Developers) used to access the data before useParams Hooks

Create User Component

Let us access the data From User Component or Page

App.jsx

import React from "react";


import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "./HooksTotal/RouterConcept/Home";
import About from "./HooksTotal/RouterConcept/About";
import Contact from "./HooksTotal/RouterConcept/Contact";
import "./App.css";
import LinksComp from "./HooksTotal/RouterConcept/LinksComp";
import ErrorComp from "./HooksTotal/RouterConcept/ErrorComp";
import User from "./HooksTotal/RouterConcept/User";
export default function App() {
return (
<BrowserRouter>
<LinksComp />
<Routes>
<Route exact path="/" element={<Home />}></Route>
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/user" element={<User/>}/>
<Route path="/user/:name" element={<User/>}/>
<Route path="*" element={<ErrorComp/>} />

</Routes>
</BrowserRouter>
);
}

142
REACT JS

User.jsx

This ‘match’ process is not working now (it is depreciated);

import React from 'react'

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

import React from "react";


import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "./HooksTotal/RouterConcept/Home";
import About from "./HooksTotal/RouterConcept/About";
import Contact from "./HooksTotal/RouterConcept/Contact";
import "./App.css";
import LinksComp from "./HooksTotal/RouterConcept/LinksComp";
import ErrorComp from "./HooksTotal/RouterConcept/ErrorComp";
import User from "./HooksTotal/RouterConcept/User";
export default function App() {
return (
<BrowserRouter>
<LinksComp />
<Routes>
<Route exact path="/" element={<Home />}></Route>
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/user" element={<User/>}/>
<Route path="/user/:name" element={<User/>}/>
<Route path="*" element={<ErrorComp/>} />

</Routes>

143
REACT JS

</BrowserRouter>
);
}

User.jsx

import React from 'react'


import { useParams } from 'react-router-dom'

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

import React from "react";


import { BrowserRouter, Routes, Route } from "react-router-dom";
import HomeLocation from "./HooksTotal/RouterConcept/HomeLocation";
import UseLocationEx from "./HooksTotal/RouterConcept/UseLocationEx";

const App = () => {


return (
<div>
<BrowserRouter>

<Routes>
<Route path="/" element={<HomeLocation />} />
<Route path="/useLoc" element={<UseLocationEx />} />

144
REACT JS

</Routes>
</BrowserRouter>
</div>
);
};

export default App;

HomeLocation.jsx

import React from 'react'


import {useNavigate } from 'react-router-dom';

export default function HomeLocation() {


const navigate=useNavigate();
const name="Hero";
return (
<div>
<h1>Hell Home Page</h1>
<button onClick={()=>{navigate("/useLoc",{state:{fname:name}})}}>UseLocationPage</button>
</div>
)
}

UseLocationEx.jsx

import React from "react";


import { useLocation } from "react-router-dom";

export default function UseLocationEx() {


const location = useLocation();
console.log(location);
return (
<div>
<h1>UseLocation Page</h1>
<h1>My Name is: {location.state.fname}</h1>
</div>
);
}

console.log(location);

145
REACT JS

Check in the console after inspecting You Can See

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

Total Time=52 Seconds

o In synchronous JavaScript, code is executed in a sequential and blocking manner.


This means that each operation waits for the previous one to complete before
moving on to the next.
o Synchronous code is straightforward to read and reason about, as the flow of
execution is linear and follows a predictable path.

146
REACT JS

Example of synchronous code:

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

Total Time=52 Seconds

 Asynchronous JavaScript, on the other hand, allows tasks to be executed independently


without waiting for each other to finish. This is especially important when dealing with
time-consuming operations, such as fetching data from a server or reading a file.
 Asynchronous operations are often handled using

1)callbacks,

2) Promises,

3)or async/await syntax in modern JavaScript.

147
REACT JS

Example of asynchronous code:

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.

Example: even though time is set to 0 milliseconds

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.

Here's an overview of the key aspects of promises in JavaScript:

Creation of Promises:

You can create a promise using the Promise constructor, which takes a function as an argument.

This function, commonly referred to as the "executor function,"

takes two parameters: resolve and reject.

These are functions that you call to indicate the success or failure of the asynchronous operation.

const myPromise = new Promise((resolve, reject) => {

// Asynchronous operation

// If successful, call resolve with the result

// If there's an error, call reject with the error

});

STATES OF A PROMISE:

A promise can be in one of three states:

 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:

Promises can be consumed using the .then() and .catch() methods.

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:

Promises support chaining, allowing you to perform a sequence of asynchronous operations in


a more readable way.

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

const notlistening = false;


const usingmobile = true;
function listenClassProperlyPromise() {
return new Promise((resolve, reject) => {
if (notlistening) {
reject({
name: "you are not listening the class",
message: "so please listen the class ",
});
} else if (usingmobile) {
reject({
name: "you are using mobile phone in the class",
message: "so please stop scrolling",
});
} else {
resolve("Thank You Listening the class Properly");
}
});
}

listenClassProperlyPromise()
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.name + "," + error.message);
});

ReactDay-30

Network Requesting and storing Data


Ajax: Asynchronous javascript and xmls

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:

1. url: The URL of the resource you want to fetch.


2. Options:Optionally, you can include a second parameter for additional options, such as
headers or the HTTP method. For example:

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:

const url="https://data. .org/v4/min/data.min.json";


fetch(url).then((response)=>{
console.log(response.status);
console.log(response.ok);
})
Output:

200

True

Difference between js Object and json(avaScript Object Notation):

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

const url = "https://data.covid19india.org/v4/min/data.min.json";


fetch(url)
.then((response) => {
if (response.ok !== true) {
throw Error("not a valid url");
}
return response.json();
})
.then((data) => {
console.log(data);
});

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)
})

Lets see the Same things in Browsers Console:

In JavaScriptPractice Folder

1)Create fetchFile.html

2)Link Asynchronous.js to 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

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);
});

Specific Data:

Here Let us Display Districts Of our Telugu States:

Asynchronous.js

const url = "https://data.covid19india.org/v4/min/data.min.json";


fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data.TG.districts);
})
.catch((error) => {
console.log(error);
});

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:

 async: This keyword is used to define a function a s asynchronous.


 An asynchronous function returns an asynchronous object known as a "promise" in
JavaScript or a "coroutine" in Python.

The async keyword is used before the function declaration.

 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:

async function fetchData(){


const response= await fetch("https://data.covid19india.org/v4/min/data.min.json")
return response.json();
}

async function fetchData2(){


const data=await fetchData();
console.log(data.TG.districts.Mahabubnagar)
}
fetchData2()

Example 2:

Async ,await and then() and catch() combinly used

async function fetchData(){


const response=await fetch("https://data.covid19india.org/v4/min/data.min.json")
return response.json();
}
fetchData().then((data)=>{
console.log(data)
}).catch((error)=>{
console.log(error)
})

Example 3:

159
REACT JS

async function fetchData() {


try {
const response = await fetch("https://data.covid19india.org/v4/min/data.min.json");

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

const data = await response.json();


console.log(data);
} catch (error) {
console.error(error);
}
}

// Call the asynchronous function


fetchData();

React Js
What is Axios?

Axios is a popular JavaScript library that simplifies the process of making HTTP requests.

It works both in the browser and on the server (Node.js).

Axios is widely used for tasks such as fetching data from APIs, sending data to servers, and
handling responses.

Why Use Axios?

Axios is preferred for several reasons:

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

4. Cancellable Requests: Axios enables the cancellation of requests, which can be


beneficial for optimizing network usage.
5. Better Browser Compatibility: Axios handles cross-browser differences effectively,
ensuring your code works reliably across various browsers.

How to Use Axios:

1. Install Axios:
o You need to install Axios. If you're using Node.js, you can do this using npm or
yarn

npm install axios


or
bash

 
 yarn add axios

 Import Axios:

import Axios:

// CommonJS
const axios = require('axios');

// ES6 Modules
import axios from 'axios';

 Make a GET Request:

axios.get('https://api.example.com/data')
.then(response => {
console.log('Data:', response.data);
})
.catch(error => {
console.error('Error:', error);
});

 Make a POST Request:

Send data in a POST request:

axios.post('https://api.example.com/post', { key: 'value' })


.then(response => {
console.log('Response:', response.data);
})
.catch(error => {
console.error('Error:', error);

161
REACT JS

});

Using Async/Await:

You can use async/await for cleaner asynchronous code:

async function fetchData() {


try {
const response = await axios.get('https://api.example.com/data');
console.log('Data:', response.data);
} catch (error) {
console.error('Error:', error);
}
}

fetchData();

Where to Use Axios:

You can use Axios in various scenarios:

 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.

Example 1:Wont Work Because the data is given in


Object Format but we are trying to access it as array
It will show this as output :state.map is not a function

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);

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);

// Update the state with the district keys


setStates(keys);
});

// The empty dependency array ensures that this effect runs only once when the component mounts
}, []);

// Render the component


return (
<>
{/* Display the title */}
<h1>Total Covid Details Using Axios</h1>

{/* 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

Create React with Vite


PS C:\Users\Admin\Desktop\ReactBatch2> npm create vite@latest then Enter

Name Your Project:


? Project name: » react-with-vite then Enter

Select The Framework(react ) here


? Select a framework: » - Use arrow-keys. Return to submit.

Vanilla

Vue

> React then Enter

Preact

Lit

Svelte

Solid

Qwik

Others

Select The Variant


? Select a variant: » - Use arrow-keys. Return to submit.

TypeScript

TypeScript + SWC

> JavaScript

165
REACT JS

JavaScript + SWC

Follow The Following Commands


Scaffolding project in C:\Users\Admin\Desktop\ReactBatch2\react-with-vite...

Done. Now run:

cd react-with-vite

npm install

npm run dev

Step 1: PS C:\Users\Admin\Desktop\ReactBatch2> cd react-with-vite

Step 2: PS C:\Users\Admin\Desktop\ReactBatch2\react-with-vite> npm install

added 269 packages, and audited 270 packages in 2m

97 packages are looking for funding

run `npm fund` for details

found 0 vulnerabilities

Step 3: PS C:\Users\Admin\Desktop\ReactBatch2\react-with-vite> npm run dev

ITE v5.0.7 ready in 625 ms

➜ Local: http://localhost:5173/ search this url in search engine’s Search Box

➜ Network: use --host to expose

➜ press h + enter to show help

166
REACT JS

You Can See Following web page in Browser

Folder Structure:

Here main.jsx is similar to index.jsx in previous react

167
REACT JS

Difference Between Previous React and Vite

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.

Here are some key differences between React and Vite:

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

1. Difference between Compiled language and Interpreted Language


2. What is JavaScript? Explain?

169
REACT JS

3. What are variables and datatypes in js ? Difference between var,let,const?


4. Create a calculator (+,-,%,x) by using external Js
5. List Es6 features and define in 1 line
6. Explain 3 types of functions with Example?
7. Explain Hoisting with example?
8. Define Prototype and Explain about it?
9. Does Polymorphism supported by Js? If not why?
10. Create a object and display the persons who can vote?
11. Create an array with 8 elements and diplay using map()?
12. create an array and display largest element of the array ?
13. Define callbyvalue,callbyreference,callback function and higher order function?
14. What is Promise and how to handle Promises explain with a Example?
15. Explain about async and await with a Example?
16. List Date and Math methods?
17. Explain forEach(),map(),filter() and reduce() with example?

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.

WHY SHOULD I USE REDUX?

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.

WHEN SHOULD I USE REDUX?

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.

Redux is more useful when:

 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.

Here are the key concepts in Redux:

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.

Here's a simple example of a Redux flow:

1. Action Creation:

const increment = () => ({


type: 'INCREMENT',
payload: 1,
});

Reducer:

const counterReducer = (state = 0, action) => {


switch (action.type) {
case 'INCREMENT':

173
REACT JS

return state + action.payload;


default:
return state;
}
};

Store Creation:

 import { createStore } from 'redux';


const store = createStore(counterReducer);

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

Command to install Redux

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.

create Actions,Reducers Folder

create index.js file inside Actions Folder

174
REACT JS

index.js

export const inCrement = () => {


return { type: "Increment" };
};
export const deCrement = () => {
return { type: "Decrement" };
};

Create index.js and UpDown.js files in Reducers Folder

updown.js

updateNumber is a reducer function

export const updateNumber=(state=0,action)=>{


if(action.type==="Increment"){
return state++;
}
else if(action.type==="Decrement"){
return state--;
}

index.js

import { updateNumber } from "./UpDown";


import { combineReducers } from "redux";
const mainReducer = combineReducers({ updateNumber });
export default mainReducer;

Create store.js in src

store.js

import { createStore } from "redux"; //deprecated


import mainReducer from "./Reducersss";

175
REACT JS

const globalstore=createStore(mainReducer);
export default globalstore;

or

use this command to use Following example

npm install @reduxjs/toolkit

import { configureStore } from "@reduxjs/toolkit"; // Make sure to import from the correct path
import mainReducer from "./Reducersss/index";

const globalStore = configureStore({


reducer: mainReducer,
// other options or middleware can be added here
});

export default globalStore;

App.jsx

useSelector is a Selector

import { useDispatch, useSelector } from "react-redux";


import { increment,Decre } from "./Actions"; // Make sure this import is correct

export default function App() {


const myState = useSelector((state) => state.updateNumber);
const dispatch = useDispatch();

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

import React from "react";


import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import globalstore from "./store.js";
import { Provider } from "react-redux";
globalstore.subscribe(() => console.log(globalstore.getState()));
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<Provider store={globalstore}>
<App />
</Provider>
</React.StrictMode>
);

Following Are the Official websites of React


Modern React : https://react.dev/blog/2023/03/16/introducing-react-dev

React Document: https://legacy.reactjs.org/docs/getting-started.html

Redux : https://redux.js.org/

177
REACT JS

tHanK - yOU

178

You might also like