react-fullnotes
react-fullnotes
b) create-react-app -version
gitIgnore - /node-modules
• JSX stands for JavaScript XML. It is a JavaScript syntax extension. Its an XML
or HTML like syntax used by ReactJS.
Allows us to write html and js in the component
React Fragments
A common pattern in React is for a component to return multiple elements.
Fragments let you group a list of children without adding extra nodes to the
DOM.
We know that we make use of the render method inside a component
whenever we want to render something to the screen. We may render a
single element or multiple elements, though rendering multiple elements will
require a ‘div’ tag around the content as the render method will only render
a single root node inside it at a time.
Ex:
Const App = () => {
return (
<div>
<h2>Hello</h2>
<p>How you doin'?</p>
</div>
);
}
Components
A Component is one of the core building blocks of React. In other words, we
can say that every application you will develop in React will be made up of
pieces called components.
Components are independent and reusable bits of code.
2 types of component
1. Functional component
2. Class component
VIRTUAL DOM
When anything new is added to the application, a virtual DOM is created and
it is represented as a tree. Each element in the application is a node in this
tree. So, whenever there is a change in the state of any element, a new
Virtual DOM tree is created. This new Virtual DOM tree is then compared
with the previous Virtual DOM tree and make a note of the changes. After
this, it finds the best possible ways to make these changes to the real DOM.
Now only the updated elements will get rendered on the page again.
PROPS
Props are arguments passed into React components. Props are passed to
components via HTML attributes. props stands for properties. React Props are
like function arguments in JavaScript and attributes in HTML. To send props
into a component, use the same syntax as HTML attributes
Export
1. Default Export
2. Named Export
Types of Hooks
1. usestate
2. Useeffect
3. usememo
4. useref
5. usecontext
6. redux
1. Counter (number)
2. Checkbox (boolean)
USESTATE
import React, { useState } from "react";
function App() {
return (
<div>
onChange={(e) => {
setFullName(e.target.value);
}}/>
setSelectBox(e.target.value);
}}>
</select>
<span>
<input
type="checkbox"
checked={checkBox}
onChange={(e) => {
//setCheckBox(e.target.checked);
setCheckBox(!checkBox)
}}
/> available</span>
<div>
</div>
</div>
);
CSS in REACT
import React, { useState } from "react";
function App() {
const applycss = {
backgroundColor: "red",
width: "200px",
height: "200px",
marginLeft: "10px",
};
return (
<div>
<div style={applycss}></div>
<div
style={{
backgroundColor: "red",
width: "200px",
height: "200px",
marginLeft: "10px",
}}
></div>
</div>
);
PROPS
import React, { useState } from "react";
function App() {
return (
<div>
<Card name="mobile"
picture="https://tse3.mm.bing.net/th?id=OIP.vbHfsrK2IfWE1ZT9NMw5PgHaE7&pid=Api&P=0&h=180"/>
<Card name="car"
picture="https://tse3.mm.bing.net/th?id=OIP.vbHfsrK2IfWE1ZT9NMw5PgHaE7&pid=Api&P=0&h=180"/>
<Card name="bike"
picture="https://tse3.mm.bing.net/th?id=OIP.vbHfsrK2IfWE1ZT9NMw5PgHaE7&pid=Api&P=0&h=180"/>
<Card name="laptop"
picture="https://tse3.mm.bing.net/th?id=OIP.vbHfsrK2IfWE1ZT9NMw5PgHaE7&pid=Api&P=0&h=180"/>
</div>
</div>
);
return (
<div>
<div className="card">
<h4>{props.name}</h4>
</div>
</div>
function App() {
const jsonResponse = [
img: "https://tse3.mm.bing.net/th?id=OIP.vbHfsrK2IfWE1ZT9NMw5PgHaE7&pid=Api&P=0&h=180",
name: "mobile",
},
img: "https://tse3.mm.bing.net/th?id=OIP.vbHfsrK2IfWE1ZT9NMw5PgHaE7&pid=Api&P=0&h=180",
name: "laptop",
},
img: "https://tse3.mm.bing.net/th?id=OIP.vbHfsrK2IfWE1ZT9NMw5PgHaE7&pid=Api&P=0&h=180",
name: "bike",
},
img: "https://tse3.mm.bing.net/th?id=OIP.vbHfsrK2IfWE1ZT9NMw5PgHaE7&pid=Api&P=0&h=180",
name: "car",
},
img: "https://tse3.mm.bing.net/th?id=OIP.vbHfsrK2IfWE1ZT9NMw5PgHaE7&pid=Api&P=0&h=180",
name: "AC",
},
];
return (
<div>
})}
</div>
</div>
);
Export Named
export function phoneValidation(value){
return regex.test(value)
function handleFunc(){
console.log(phoneValidations, 'phoneValidation')
return (
<div>
</div>
Package Toastify
import { useState } from "react";
import "react-toastify/dist/ReactToastify.css";
if(!phoneValid){
return;
return (
<div>
<ToastContainer />
<input
type="number"
value={number}
/>
Submit
</button>
</div>
);
};
import "react-toastify/dist/ReactToastify.css";
setUserInfo(user);
console.log("render ");
useEffect(() => {
callingGetApi();
console.log("useeffect ");
}, []);
return (
<div>
<ToastContainer />
/>
{userInfo.brand}
{userInfo.category}
</div>
);
};
useEffect
The useEffect Hook allows you to perform side effects in your components.
1. No dependency passed:
useEffect(() => {
//Runs on every render
});
2. An empty array:
useEffect(() => {
//Runs only on the first render
}, []);
Ex:
useEffect(() => {
console.log("useeffect ");
}, [number]);
Routes
import React from "react";
return (
<div>
<BrowserRouter>
<Routes>
</Routes>
</BrowserRouter>
</div>
);
};
return (
<div>section</div>
return (
<div>about</div>
return (
<div>contact</div>
</div>
);
};
LINK
import { Link } from "react-router-dom";
return (
<div style={applyCss}>
<div><h3>Header</h3></div>
<div style={applyCss}>
</div>
</div>
Navigate
return (
<>
</>
};
return (
<div>
<BrowserRouter>
<Routes>
</Routes>
</BrowserRouter>
</div>
)
}
Menulist.js
import React from 'react';
console.log(id, "selectedID")
navigate(`./menu-description/${id}`)
return (
<div>
<div>menulist</div>
{jsonResponse.map((item, index)=> {
})}
</div>
</div>
selectedId = selectedId[4];
useEffect(() => {
});
setDescription(result);
}, []);
return (
<div>
<h2>menuDescription</h2>
{description.map((item) => {
return (
<p>{item.description}</p>
</div>
);
})}
</div>
);
};
return (
<p>{props.name}</p>
</div>
JSON Response
img: "https://tse3.mm.bing.net/th?id=OIP.vbHfsrK2IfWE1ZT9NMw5PgHaE7&pid=Api&P=0&h=180",
name: "mobile",
id: 1,
description: "A mobile phone is a wireless handheld device that allows users to make and
receive calls. While the earliest generation of mobile phones could only make and receive
calls, today’s mobile phones do a lot more, accommodating web browsers, games, cameras, video
players and navigational systems. The first mobile phones, as mentioned, were only used to
make and receive calls, and they were so bulky it was impossible to carry them in a pocket.
These phones used primitive RFID and wireless systems to carry signals from a cabled PSTN
endpoint. Later, mobile phones belonging to the Global System for Mobile Communications (GSM)
network became capable of sending and receiving text messages. As these devices evolved, they
became smaller and more features were added, such as multimedia messaging service (MMS), which
allowed users to send and receive images"
},
img: "https://images-na.ssl-images-amazon.com/images/I/812NShN3MpL._SL1500_.jpg",
name: "laptop",
id: 2,
description: "A mobile phone is a wireless handheld device that allows users to make and
receive calls. While the earliest generation of mobile phones could only make and receive
calls, today’s mobile phones do a lot more, accommodating web browsers, games, cameras, video
players and navigational systems. The first mobile phones, as mentioned, were only used to
make and receive calls, and they were so bulky it was impossible to carry them in a pocket.
These phones used primitive RFID and wireless systems to carry signals from a cabled PSTN
endpoint. Later, mobile phones belonging to the Global System for Mobile Communications (GSM)
network became capable of sending and receiving text messages. As these devices evolved, they
became smaller and more features were added, such as multimedia messaging service (MMS), which
allowed users to send and receive images"
},
img: "https://wallpapercave.com/wp/wp1925045.jpg",
name: "bike",
id: 3,
description: "A mobile phone is a wireless handheld device that allows users to make and
receive calls. While the earliest generation of mobile phones could only make and receive
calls, today’s mobile phones do a lot more, accommodating web browsers, games, cameras, video
players and navigational systems. The first mobile phones, as mentioned, were only used to
make and receive calls, and they were so bulky it was impossible to carry them in a pocket.
These phones used primitive RFID and wireless systems to carry signals from a cabled PSTN
endpoint. Later, mobile phones belonging to the Global System for Mobile Communications (GSM)
network became capable of sending and receiving text messages. As these devices evolved, they
became smaller and more features were added, such as multimedia messaging service (MMS), which
allowed users to send and receive images"
},
img: "http://wallup.net/wp-content/uploads/2016/07/21/397775-car-sports_car-Super_Car-
nature-landscape-road-clouds-Audi-Audi_R8-field-mountains-hills-sun_rays-plants-blue_cars-
vehicle.jpg",
name: "car",
id: 4,
description: "A mobile phone is a wireless handheld device that allows users to make and
receive calls. While the earliest generation of mobile phones could only make and receive
calls, today’s mobile phones do a lot more, accommodating web browsers, games, cameras, video
players and navigational systems. The first mobile phones, as mentioned, were only used to
make and receive calls, and they were so bulky it was impossible to carry them in a pocket.
These phones used primitive RFID and wireless systems to carry signals from a cabled PSTN
endpoint. Later, mobile phones belonging to the Global System for Mobile Communications (GSM)
network became capable of sending and receiving text messages. As these devices evolved, they
became smaller and more features were added, such as multimedia messaging service (MMS), which
allowed users to send and receive images"
},
img: "https://assets.hardwarezone.com/img/2014/02/LG_Inverter_AC_2.jpg",
name: "AC",
id: 5,
description: "A mobile phone is a wireless handheld device that allows users to make and
receive calls. While the earliest generation of mobile phones could only make and receive
calls, today’s mobile phones do a lot more, accommodating web browsers, games, cameras, video
players and navigational systems. The first mobile phones, as mentioned, were only used to
make and receive calls, and they were so bulky it was impossible to carry them in a pocket.
These phones used primitive RFID and wireless systems to carry signals from a cabled PSTN
endpoint. Later, mobile phones belonging to the Global System for Mobile Communications (GSM)
network became capable of sending and receiving text messages. As these devices evolved, they
became smaller and more features were added, such as multimedia messaging service (MMS), which
allowed users to send and receive images"
},
];
useRef
useRef is a React Hook that lets you reference a value that’s not needed for
rendering.
The useRef is a hook that allows to directly create a reference to the DOM
element in the functional component
//Ex:
import React , {useRef} from 'react'
function handleFunc() {
inputText.current.focus();
inputText.current.style.color = "red"
return (
<div>
</div>
)
useMemo
useMemo is a React Hook that lets you cache the result of a calculation
between re-renders.
Ex:
import React, { useEffect, useMemo, useState } from 'react'
return handleSquareNumber(number)
}, [number])
function handleSquareNumber(number){
return (
<div>
</div>
useContext
useContext is a React Hook that lets you read and subscribe to context from
your component.
return (
<div>
<themeContext.Provider value={toggleBtn}>
<Header />
</themeContext.Provider>
</div>
}
export default Demo
Child component
import React, {useContext} from 'react'
return (
<div style={toggleValue ?
Higher-order components
In React, a higher-order component is a function that takes a component as
an argument and returns a new component that wraps the original
component.
HOC are a powerful feature of the React library. They allow you to reuse
component logic across multiple components.
Menu List
console.log(id, "selectedID");
navigate(`./menu-description/${id}`);
};
return (
<div>
return (
<div key={item.id}>
{item.bestSeller ? <BestSellerComponent
id={item.id}
img={item.img}
name={item.name}
selectedCard={handleSelectedCard}
/> : <Card
id={item.id}
img={item.img}
name={item.name}
selectedCard={handleSelectedCard}
/> }
</div>
);
})}
</div>
</div>
);
};
return(props) => {
console.log(props, 'props...')
return (
<div style={{position:'relative'}}>
<BestSellerComponent
{...props}/>
</div>
Json Response
img: "https://tse3.mm.bing.net/th?id=OIP.vbHfsrK2IfWE1ZT9NMw5PgHaE7&pid=Api&P=0&h=180",
name: "mobile",
id: 1,
bestSeller: true,
description: "decription"
},
img: "https://images-na.ssl-images-amazon.com/images/I/812NShN3MpL._SL1500_.jpg",
name: "laptop",
id: 2,
bestSeller: false,
description: "decription"
},
img: "https://wallpapercave.com/wp/wp1925045.jpg",
name: "bike",
id: 3,
bestSeller: false,
description: "decription"
},
img: "http://wallup.net/wp-content/uploads/2016/07/21/397775-car-sports_car-Super_Car-
nature-landscape-road-clouds-Audi-Audi_R8-field-mountains-hills-sun_rays-plants-blue_cars-
vehicle.jpg",
name: "car",
id: 4,
bestSeller: true,
description: "decription"
},
img: "https://assets.hardwarezone.com/img/2014/02/LG_Inverter_AC_2.jpg",
name: "AC",
id: 5,
description: "decription",
bestSeller: false,
},
];
Css
.best-seller-tag {
position: absolute;
top: 0;
left: 10px;
margin: 0;
background-color: #000;
color: #fff;
padding: 5px;
border-radius: 2px;
REDUX
its core building blocks work, such as store, actions, and reducers and how
they all come together and make Redux the global state management library.
Why Redux ?
To pass data from one component to another in a large application and
facilitate debugging, it can become challenging. That's why global state
management was introduced.
store
import { configureStore } from "@reduxjs/toolkit";
reducer: {
cart: CartSlice,
profile: [],
})
Cartslice
import { createSlice } from "@reduxjs/toolkit";
const CartSlice = createSlice({
name: "cart",
initialState: {
cartState: []
},
reducers: {
state.cartState.push(action.payload)
})
Header
import React from "react";
return (
<p>Header {props.id}</p>
<div>
<span className="cartvalue">{cartInfo.length}</span>
</div>
</div>
</div>
);
};
export default Header;
Card
import Button from 'react-bootstrap/Button';
dispatch(addItem(info))
return (
<div className="card">
<p>{props.name}</p>
</div>
</div>
Custom Hooks
import React from "react";
if (error) {
return <div></div>;
usehandleApiCall
import { useState, useEffect } from "react";
useEffect(() => {
fetchData();
}, [url]);
try {
method: type,
body,
});
setData(result);
} catch (error) {
setError(error);
}
};
Object-Oriented Programming(OOP)
Object-Oriented Programming(OOP) is a programming paradigm(pattern)
based on the concepts of Objects.
1. Object
2. Class
3. Encapsulation
4. Inheritance
5. polymorphism
Object
Objects are like real-life entities. They have their properties and methods.
const person = {
name: "ram",
age: 22,
greet: function(){
return `Hello ${this.name}, you are ${this.age} years old`
}
}
console.log(person.greet());
Class
Class is a blueprint of a real-life entity. It describes how the object will look
alike, what characteristics it holds and what kind of actions we can perform on
it.
class User {
this.name = name;
this.userName = userName;
this.password = password;
login(userName, password) {
console.log('Login Successfully');
} else {
console.log('Authentication Failed!!');
};
classroom.login("yogeshh", "yogesh@98")
Constructor - A constructor enables you to provide any custom initialization that must be done
before any other methods can be called on an instantiated object.
Encapsulation
encapsulation is a concept that involves bundling data (attributes) and methods (functions) that
operate on the data into a single unit, usually known as an object. This helps in organizing and
protecting the internal state of an object from outside interference.
// Private variables
this.getMake = function () {
return _make;
};
this.getModel = function () {
return _model;
};
_model = newModel;
};
myCar.setModel('Corolla');
Encapsulation helps in hiding the internal implementation details of an object and provides a clean
and controlled interface for interacting with the object.
Inheritance
When one class derived the properties and methods of another class it is
called inheritance
The class that inherits the property is known as subclass or child class and the
class whose properties are inherited is known as a superclass or parent class.
class User {
#password;
constructor(email, password) {
this.email = email;
this.#password = password;
login(email, password) {
console.log('Login Successfully');
} else {
console.log('Authentication Failed!!');
}
class Author extends User {
constructor(email, password) {
super(email, password);
In the above example, the Author and Admin classes inherit the property of
the User class using extends and super keywords.
Sub-class has access to all the public and protected members of a superclass.
In addition, It can have its own properties and methods. This is how we can
achieve reusability through inheritance.
The super keyword is a special keyword. Calling super in the child's constructor
invokes the parent constructor. That's how we are initialising the properties in
the Author and Admin classes.
The child class can also override the methods of a parent class. This introduces
the concept of polymorphism.
Polymorphism
class User {
constructor(email, password) {
this.email = email;
this.password = password;
login(email, password) {
} else {
console.log("Authentication Failed!!");
constructor(email, password) {
super(email, password);
constructor(email, password) {
super(email, password);
login(email, password) {
} else {
console.log("Authentication Failed!!");
Here, the Author and Admin both inherit the User class. Both classes have
the login method of the User class. Now I need some extra level of verification
for the admin account, so I have created a login method in the Admin class. It
will override the parent's login method.
When an object of the Admin class calls the login method, it will invoke a
function call to the login method of the Admin class.
Class component
constructor(props) {
super(props);
this.state = {
name: "",
};
componentDidMount() {
console.log("componentDidMount calling...");
componentDidUpdate(prevProps, prevState) {
console.log("componentDidUpdate calling...");
}
}
render() {
return (
<div>
<input
type="text"
value={this.state.name}
/>
</div>
);
Constructor
Constructor is a method that is used to create and initialize an object created
with a class and this must be unique within a particular class.
• It is used to initialize objects i.e, State in ReactJS.
• It is used to read or access a parent’s property from a child’s
component in ReactJS
Super: Super is a keyword that is used to call the parent’s class method and
data. It is used for the inheritance model of class.
Lifecycle of Components
lifecycle of a component can be defined as the series of methods that are
invoked in different stages of the component’s existence.
• Initialization: This is the stage where the component is constructed
with the given Props and default state. This is done in the constructor of a
Component Class.
• Mounting: Mounting is the stage of rendering the JSX returned by
the render method itself.
• Updating: Updating is the stage when the state of a component is
updated and the application is repainted.
• Unmounting: As the name suggests Unmounting is the final step of
the component lifecycle where the component is removed from the page.
Initialization
In this phase, the developer has to define the props and initial state of the
component this is generally done in the constructor of the component. The
following code snippet describes the initialization process.
class Clock extends React.Component {
constructor(props)
{
// Calling the constructor of
// Parent Class React.Component
super(props);
Mounting
Mounting is the phase of the component lifecycle when the initialization of
the component is completed and the component is mounted on
the DOM and rendered for the first time on the webpage.
• First initialize the data and the states in the constructor
• componentDidMount() Function: This function is invoked right after
the component is mounted on the DOM i.e. this function gets invoked
once after the render() function is executed for the first time
Update
Updation is the phase where the states and props of a component are
updated followed by some user events such as clicking, pressing a key on
the keyboard, etc.
·
setState() Function: This function is used to update the state of a
component.
Unmounting
This is the final phase of the lifecycle of the component which is the phase of
unmounting the component from the DOM. The following function is the
sole member of this phase.
• componentWillUnmount() Function: This function is invoked before
the component is finally unmounted from the DOM i.e. this function gets
invoked once before the component is removed from the page and this
denotes the end of the lifecycle.
useEffect(() => {
console.log("componentDidUpdate is running...")
}, [name])
return (
<div>
<h2>Functional Component</h2>
<p>{props.info}</p>
<input type='text' placeholder='enter name'
value={name}
<p>{name}</p>
</div>
constructor(props) {
super(props);
this.state = {
name: "yogesh",
phoneNumber: "",
};
// componentDidMount - this will call only one time when the page reloads
componentDidMount() {
console.log("3")
console.log("componentDidMount is running...");
componentDidUpdate(prevprops, prevState) {
console.log("componentDidUpdate is running...")
}
componentWillUnmount(){
alert("componentWillUnmount")
console.log("componentWillUnmount is running...")
render() {
console.log("1")
return (
<div>
<h2>Class Component</h2>
<p>{this.props.info}</p>
{console.log("2")}
<input
type="text"
placeholder="enter name"
value={this.state.name}
onChange={(e) => {
}}
/>
<p>{this.state.name}</p>
</div>
);
Bundle- refers to a single, minified, and compressed JavaScript file that contains all the code
needed for a particular part or the entirety of a web application. Bundling is a common practice in
modern web development to optimize the loading and execution of JavaScript code.
return (
<div>
<BrowserRouter>
<Routes>
</Routes>
</BrowserRouter>
</div>
);
};