β Js library used to create UI
β library = A programming library is a collection of prewritten code that programmers can use to optimize tasks ( in C lang we use the pow(a,b) pre-defined function with using stdlib.h library
β React is all about components so it is component based architecture
βββββββββββββββ
β JS is based on imparative approach
β React is based on declarative approach
β imparative approach means line by line
β declarative approach means we
β SPA ( single page application ) approach (like netflix )
β Development is faster than vanilla JS
β React alternatives = angularJs , vueJs
- reusablity (using components)
- DRY (do not repeate yourself)
- readability
- SOC(seperation of concern)
- maintainability
βββββββββββββββ
β a piece of code that used multiple times - reusable piece of code
β ( like custom html element that we can use multiple times )
β same work as Function ( create js file and write function )
βββββββββββββββ
β Install node js ( link and check node -v
and npm -v
)
β Vs code
β React installation ( vidLink )
β if above is not working then try this
βββββββββββββββ
β package.json = dependencies/version/scripts are avialabe here
β src folder
src > index.js = first file that excecutes when page load / entry point of js = here react creates 'root' that fetch from index.html
src > index.css
= file that contains css for index.js file
src > app.js or app.jsx
β public folder
public > index.html = contains 'root'
β nodeModules folder
index.js
file then it goes to index.html
file to get the <root>
div and it converts rootDiv to react-root and then it render <App>
from App.js
or App.jsx
and here App.js
contains html code
βββββββββββββββ
βββββββββββββββ
βοΈ β first create components
folder in src
βοΈ β then src > components then create Item.js
and Item.css
βοΈ β Item.js
looks like
import './Item.css' ; //here first import .css file
function Item() //then create function that returns Html code
{
return(
// html codes
<p className="parth"> hello </p>
);
}
export default Item ; //then export the function that we can use in App.js
here in Item.js
we are actually writing JSX (JavaScrpit XML means JS with Html code) code so we cannot define html element class directly because js already have predefined class component so here in jsx we have to use className='xxxxx'
except class='xxxxx'
ββββββββββ
βοΈ β Item.css
looks like
.parth
{
text-align: center;
background-color: aqua;
}
// same as actual css
ββββββββββ
βοΈ β use of component in App.js
file
import Item from './components/Item' ; // here we are importing Item from `Item.js`
// components > Item(exported)
function App()
{
return(
// html codes
// using Item componenet
<Item> </Item>
);
}
export default App; // exporting `App.js` because we have to use this in `index.js` the first entry point
ββββββββββ
βοΈ β EXTRA index.js
looks like this
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render( <App /> );
βββββββββββββββ
βββββββββββββββ
π€ Extra - In JSX how to use varibales value
function any()
{
const var = 5 ;
return (
<p> {var} </p>
);
}
βββββββββββββββ
βββββββββββββββ
βοΈ β here we have to send properties from App.js
file like this
function App()
{
const itemTwoName = "patel" ; //β οΈ here we are doing PARENT to CHILD communcation using props matlab parent kuch value send kar rha hai child ko
return (
<div>
//one way
<item name = "parhu" > </item>
//second way
<item name ={ itemTwoName } > </item>
//children of prop
<item> i am children which is between and inside the component </item>
</div>
);
}
βοΈ β in Item.js
we have to change things like
function Item(props)
{
const pname = props.name ;
return(
<div> // IMP = if there are more than one html line then put them into <div> TAG
<p> {pname} </p>
{ props.children } // here we can acces " i am children..."
</div>
);
}
//---------------------------------------
function Item( {name,children} ) // here "name" that we have sended and "children" is bydefault to access children
{
return(
<div>
<p> {pname} </p>
{ children } // here we can acces " i am children..."
</div>
);
}
βββββββββββββββ
βββββββββββββββ
function clickHandlerFunction()
{
//anything that you want to perform
}
// Event Handling
<button onClick={clickHandlerFunction} > xxxx </button>
// another way
<button onClick={() => {
clickHandlerFunction();
}}>
xxxx
</button>
callbackFuntion
avoid to write this callbackFuntion()
beacuse ()
means that automatically calls the function without any Event done
βββββββββββββββ
βββββββββββββββ
β for Re-Rendering purpose
β like i want to change innerText / value updation of any element when i click on the button but to do this i have to do Re-Rendering
β Before state
function clickedBtn()
{
const title = "oldValue" ;
function cbFunc()
{
title = "newValue" ;
}
return(
<div>
<h2> {title} </h2>
<button onClick={cbFunc} > xxxx </button>
</div>
);
}
// π here first react render the whole DOM so the value of title = "oldValue" and it print "oldValue" in <h2> tag but when we clicked on
// <button> tag that time the value of title = "newValue" changed so that time again Render is not possible and the again print is not possible so NOT any CHANGES in <h2> tag output
β βοΈ After state
import React, {useState} from 'react'; // first import {useState} which is react-Hook(utility function)
function clickedBtn()
{
const [title,valueUpdateFunc] =useState("oldValue"); //useState returns 2 things as array form first is newValue of variable and function for updating value (using destructing js method)
// syntax = const [variableName , valueUpdateFunc] = useState("oldValue");
function cbFunc()
{
valueUpdateFunc("newValue");
}
return(
<div>
<h2> {title} </h2>
<button onClick={cbFunc} > xxxx </button>
</div>
);
}
// π after clicked on <button> there is also re-Redering and the value of <h2> updated to new value on UI
π HomeWork =
1 = Why React Hook useState uses const and not let
2 = what is immutable react js - combined with useState que
3 = React setState/useState happens instantly or takes time
π¨ EROORS=
β img is a void element tag and must neither have children
nor use dangerouslySetInnerHTML
. ==> then write <img />
in just single closing
π Extra for FORM =
β get the value of input field that inserted by user using (event) and event.target.value
word
β how to set value of any text field value = { xyz }
it can set value as "xyz" in inputfield
β app.js
means PARENT looks like this
function App() {
function ParentValue(data)
{
console.log(data);
}
return (
<div>
<Child ParentValueFunc={ParentValue}></Child> //here using props we are sending function to the Child
</div>
);
}
β Child.js
means CHILD looks like
function Child(props){
props.ParentValueFunc("dataaa Inside secreate"); //here ParentValueFunc get the parameter as data = "dataaa Inside secreate"
return(<p>hell insider here</p>);
}
so we can send the value from CHILD to PARENT using function with parameter like above
βββββββββββββββ
βββββββββββββββ
β manage side-effects (if i do any action at one component then there is also some changes on another component - ex.changing doc title, modifying state of parent component,api calls,changes in DOM )
β every RENDER of UI useEffect will excecute
β agar aap kuch kaam karwane chahte ho UI render means UI me changes hone k baad tab aap useEffect use kar sakte ho
import {useEffect, useState} from "react"; // first import
function App()
{
const [text,setText] = useState('') ;
//------------------------------------------
// VARIATION-1οΈβ£ (every render)
useEffect( () => {
console.log("UI render Done");}
);
//------------------------------------------
// VARIATION-2οΈβ£ (first render - when app.js fully renderd for first time)
useEffect( ()=>{
console.log("UI rendere done");
},[] );
//------------------------------------------
//VARIATION-3οΈβ£ (first render + whenever dependency changes) // firts render + whenever variable "text" changes this useEffect runs
useEffect(()=>{
console.log(" text changed observed");
} , [text] )
//------------------------------------------
//VARIATION-4οΈβ£ (to handle unmounting of components)
useEffect(()=>{
//add event listener
console.log("listener added");
return ()=>{ console.log("listener removed"); }
}) //IMP= first run "listener removed" then run "listener added"
// OR-----------
useEffect(() => {
const handleClick = () => {
console.log('Button clicked!');
};
// Add event listener when component mounts
// generally with hight and width types of or mouse move x,y poisition types of events
console.log('Listener added');
document.addEventListener('click', handleClick);
// Remove event listener when component unmounts
return () => {
console.log('Listener removed');
document.removeEventListener('click', handleClick);
};
}, []);
//---------------------------------------------------------------------------------
function changeHandler(event){
setText(event.target.value)
console.log(text);
}
return (
<div className="App">
<input type="text" onChange={changeHandler} />
</div>
);
}
βββββββββββββββ
βββββββββββββββ
β using array , if we want to create multiple components at a time then use array.map( callBackFunc )
β if we want to do filter then use array.filter (callBackFunc)
items.map( (item)=> { return (<div>{item}</div>) } );
βββββββββββββββ
βββββββββββββββ
β form handleing is difficult in js because everytime we have to create different functions to save the value of all fields in form
function App()
{
const [formData,setFormData] = useState(
{
firstName : "" ,
lastName : "",
}
);
function changeHandler(event){
setFormData( (prevFormData)=>{
return {
...prevFormData,
[event.target.name] : event.target.value
}
} )
}
return (
<div>
<form>
<input type="text" placeholder="first name" onChange={changeHandler} name="firstName" ></input>
<input type="text" placeholder="last name" onChange={changeHandler} name="lastName"></input>
</form>
</div>
);
}
// here every changes on <input> tag , the changeHandler function will run
// and in function setFormData will take return the object with value which is already named as `formData`
// the under process in return => it take previousObject with all changed properties and then access that property using the `name` that given in html element
// means 1) previous state copy 2) element trigger and value update
β JS topic= referance link of spread operator with object
βββββββββββββββ
β maintain state inside component
<input type="text" placeholder="first name" onChange={changeHandler} name="firstName" value={formData.firstName}></input>
<input type="text" placeholder="last name" onChange={changeHandler} name="lastName" value={formData.lastName} ></input>
// here we are also re-rendering values from formData object in the components
// matalab jab bhi formData ki state change hogi then tab har ek components jisme value={formData.something} dali hui hai uski value b re-render hogi
// bascially formData me jo bhi value aarhi hai usko hum uske original components me update kar rhe hai
β some imp of react form handeling with checkBox
βββββββββββββββ
βββββββββββββββ
β SPA - single page application ( only one html file where changes happens dynamically and if you click anywhere no reloading )
β React Router is a popular library for handling routing in React applications.(route-path)
β it allows you to create single-page applications with multiple views, each represented by a specific URL.
β This makes it possible to navigate between different sections(homepage,about,support section) of your application without triggering a full page reload.
// installation
npm install react-router-dom
β then index.js
page
import { BrowserRouter } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
β then creates different Components like Home,Support,NotFound
β then in app.js
import { Routes, Route, Link, NavLink} from "react-router-dom";
// and import all pages(components) here
function App(){
return (
<div>
<div>
<Link to="/">Home</Link> //here "Link" works like <a> tag and "to" works like href="/" attribute
<NavLink to="/support">support</NavLink> //here "NavLink" is same as "Link" but it adds .active class in active component so easy to identify active
</div>
<Routes>
<Route path="/" element={<Home/>}></Route>
<Route path="/support" element={<Support/>}></Route>
<Route path="*" element={<NotFound/>}></Route> // * means universal excluding mentioned paths
</Routes>
</div>
)
}
β here "/" is home and "/support" is the child of / (home) > /support --- and because of this we can do NESTED ROUTING
β / Β Β Β Β Β Β ---> parent
β /support Β Β Β ---> in / there is support --- child
β /about Β Β Β ---> in / there is about --- child
// nested-routing
<Routes>
<Route path="/" element={<Home/>}>
<Route path="/support" element={<Support/>}></Route>
<Route path="*" element={<NotFound/>}></Route>
</Route>
</Routes>
β but here parent element wo child route element ko render nhi hone de raha matalab sab urls par sirf homePage he open ho raha hai
βββββββββββββββ
β <Outlet>
parent route element ke andar child route elemnt ko render karne ki permission deta hai
<Routes>
<Route path="/" element={<Mainheader/>}>
<Route index element={<Home/>}></Route> // index means default route
<Route path="/support" element={<Support/>}></Route>
<Route path="/about" element={<About/>}></Route>
<Route path="*" element={<NotFound/>}></Route>
</Route>
</Routes>
β in Mainheader
component
import { Outlet } from "react-router-dom" ;
function Mainheader ()
{
return ( <Outlet></Outlet> )
}
β <Route index>
matches only when the URL path exactly matches the parent route's path and is typically used for rendering default content within a section of your app.
β <Route path="*">
acts as a catch-all route, rendering its component when no other route has matched the URL path. It's often used to handle undefined routes or show error pages.
βββββββββββββββ
βββββββββββββββ
β navigation through anywhere
β here in Labs
page component
import { useNavigate } from "react-router-dom" ;
const Labs =()=>{
const navigate = useNavigate();
function clickHandler(){
navigate("/about"); // here ("url") means navigate to "url"
}
function backHandler(){
navigate(-1); // here (-1) means it navigate to the BACK (PREVIOUS) opened page
}
return(
<div>
<div>
this is labs page
</div>
<button onClick={clickHandler}>move to about page</button>
<button onClick={backHandler}>Go Back </button>
</div>
)
}
βββββββββββββββ
ββοΈ useParams() hook - chatGpt
ββοΈEXTRA imp = add infinite scrolling reactJs library
βββββββββββββββ
βββββββββββββββ
βοΈ REACT conditional Operators
βββββββββββββββ
βββββββββββββββ
β installing
npm install axios
β using
import axios from "axios";
async function fetchData(){
const url = `https://api.giphy.com/v1/gifs/random?api_key=${API_KEY}`;
const output = await axios.get(url);
console.log(output);
}
useEffect(()=>{fetchData()} , [])
βββββββββββββββ
βββββββββββββββ
β avoid code duplication
β DRY coding + yt explained shortest
β custom hooks explained
β thapa technical yt
βββββββββββββββ
βββββββββββββββ
β Prop Drilling
β what is Prop Drilling ? and disadvantages
β what is Prop Drilling ?
β State Lifting UP
β what is ? - send data from child to parents using propFunction
β we are sending props from one parent to the child1 then child2 then child3 then child4 - and here the child1, child2, child3 do not need the data but if we want to pass the data from parent to the child4 then we have to do it
β it reduce redundancy and performance
β so the solution to send data from parent to child4 without including the child1,2,3 -- is context api
β Rules:
β createContext() = creation of context
β provider = context provide
β consume
βοΈ jis component me context provide kar rhe hai wo component and us component ke sabhi childrens uus value ko use kar sakte hai --means decenteralized value create kar rhe hai
βββββββββββββββ
β firstly created a folder named "context" and then created a file named "AppContext.js" in that
export const AppContext = createContext();
function AppContextProvider( {children} ) //π children means `<App />`
{
const [loading,setLoading] = useState(false);
const [page,setPage] = useState(1);
// data filling
if(page==1){
setPage(page+1);
}
function handlePageChange(page){
setPage(page);
}
const value = { //βοΈ value is Object
loading,
setLoading,
page,
setPage,
handlePageChange
}
// π― AppContext.Provider because we have created AppContext as createContext
return <AppContext.Provider value={value}> //βοΈ we are using above value obj
{children} //π children means `<App />`
</AppContext.Provider>;
}
β we want to use AppContextProvider() on App.js
and their children
β so in index.js
file we are doing this and here we are sending <App/>
component as {children} in the "AppContext.js"
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<AppContextProvider>
<App />
</AppContextProvider>
);
import { AppContext } from "../context/AppContext";
const value = useContext(AppContext);
// or
const { loading } = useContext(AppContext);
βββββββββββββββ
βββββββββββββββ
β useSearchParams()
β useLocation()
β LoveBabbar-guide
βββββββββββββββ
βββββββββββββββ
β what is and why ?
βοΈ Installation
npm install @reduxjs/toolkit react-redux
βοΈ create Slice = slices canbe single or multiples ( like SLICEs of one pizza and they create a whole pizza that is STORE )
//π src > redux folder > slices folder > CounterSlice.js
import { createSlice } from "@reduxjs/toolkit";
//π³οΈβπ createSlice mei 3 things ayegi 1)name 2)initialState 3)reducers means obj jis k andar sab functions honge
const initialState={
value : 0,
}
export const CounterSlice = createSlice({
name: 'counter',
initialState,
reducers : {
increment : (state) => {
state.value += 1;
},
decrement : (state) =>{
state.value -= 1;
}
}
})
// π in every slice
export const { increment, decrement } = CounterSlice.actions; //exporting functions from actions
export default CounterSlice.reducer; //exporting reducer
βοΈ create Store = store k andar sab slices ayegi ( store global state/centeralized state hogi jiske andar sab states store hogi in form of slices )
//π src > redux folder > store.js
import { configureStore } from '@reduxjs/toolkit';
import CounterSlice from './slices/CounterSlice';
const store = configureStore({
reducer : {
counter : CounterSlice , // idhar "reducer" obj k andar sabhi slides ayegi ==> name : sliceName
}, // agar ERRORS aarhe hai like( Store does not have a valid reducer) toh `CartSlice.reducer` try kro
})
export default store;
βοΈ Connect reduxToolkit with reactJs using <Provider>
import { Provider } from "react-redux";
import store from "./redux/store";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<Provider store={store} >
<App />
</Provider>
);
// aab <App/> k andar k sare components use kar payenge redux States ko
βββββββββββββββ
import { useSelector } from "react-redux";
const value = useSelector( (state)=> state.counter.value )
//πEXPLAINED----------------------------------------------------------------
// here useSelector( callBack function that returns the value )
// sabse pehele call store me jati hai then wo slice me jati hai
// state => { counter: {value: 0} }
// state.counter => {value: 0}
// state.counter.value => 0
// matlab "state" k andar sabhi slices hongi and us slices k andar unki value hongi
// idhar sirf ek slice hai jiska name "counter" diya tha and uski initialState(initialValue) = 0 define ki thi
βββββββββββββββ
import { useDispatch} from "react-redux";
import { decrement, increment } from "../redux/slices/CounterSlice";
function CounterComponent()
{
const dispatch = useDispatch();
return(
<div>
<button onClick = { ()=>dispatch( increment() ) } > Increment </button>
<button onClick = { ()=>dispatch( decrement() ) } > Decrement </button>
</div>)
}
βββββββββββββββ
βοΈ Access Input parameters using "action.payload"
.
.
.
reducers : {
add : (state,action) => { ( state + action.payload ) } //state means present value -- and -- action.payload means passed argument
}
//-------------------------------
//passed arguments from anywhere
dispatch(add(5)) ;
πΌredux devTool extension for checking all presentState
β€οΈβ€οΈπβ€οΈβ€οΈ IMP READABLE chatgpt - with combinereducer
βββββββββββββββ
βββββββββββββββ
β if you want to use multiple useState() then to avoid this you can use this
β technical-thapa
β gpt
π¨ Explained in amazon clone by cleaver programmer
β with context-api
//π src > context > StateProvider.js
import React, { createContext, useContext, useReducer } from "react";
export const StateContext = createContext();
export const StateProvider = ({ reducer, initialState, children }) => (
<StateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StateContext.Provider>
);
//anywhere we can use useStateValue() instead of using useContextHOOK which is useContext(StateContext)
export const useStateValue = () => useContext(StateContext);
β reducer file which have reducer initialState and reducer
//π src > context > reducer.js
export const initialState = {
user: null,
playlists: [],
}
const reducer = (state, action) =>
{
console.log(action);
switch (action.type) // we can also use IF-ELSEIF-ELSE here insted of switch
{
case "SET_USER" :
return {
...state,
user: action.user,
};
case "SET_PLAYLISTS" :
return {
...state,
playlists: action.playlists,
};
default :
return state;
}
}
export default reducer;
β how to joint context-api
// π index.js
import reducer, { initialState } from "./reducer"; //π src > context > reducer.js
ReactDOM.render(
<React.StrictMode>
<StateProvider initialState={initialState} reducer={reducer}>
<App />
</StateProvider>
</React.StrictMode>,
document.getElementById("root")
);
β use useReducer() hoook
const [state,dispatch] = useDataLayerValue();
//or
const [state,dispatch] = useContext(stateContext);
//or
const [{user,playlists} ,dispatch] = useDataLayerValue(); //console.log(user); -- everytime updated like useState
//console.log("state ==",state); // initialValues {user: null,playlists: []} OTHERWISE latestValuesOfInitialState {user: "updatedValue",playlists: []}
//console.log("dispatch ==",dispatch); // function to set initialValues
dispatch({
type : "SET_USER",
user : "updatedValue",
});
βββββββββββββββ
βββββββββββββββ
β use reference have 2 uses examples
β example 2 is like .getElementbyId and .getElementbyClassname after doing ref.current
β example 2 of getting DOM element
βββββββββββββββ
βββββββββββββββ
βββββββββββββββ
βββββββββββββββ
β maintaining clickHandler or any function inside mapped component that render many times
// ye component map function k andar hoga so many timne run hoga ye same component
function clickHandler(item){
//
}
return(
<div
onClick={()=>{clickHandler(item)}} // avoid to do like this "onClick={clickHandler(item)}"
>
</div>
)
β react toaster means notification popup - link
π― by LoveBabbar
π― random
π― by tutorialsPoint
π― imp topics to learn
βββββββββββββββ
β»οΈ @ Created by Parth with π