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

React Notes

react

Uploaded by

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

React Notes

react

Uploaded by

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

"Imperitive programming" in coding means -> whenever

we are updating any variable , then we are also writing


code to update it inside the dom.-> but declarative
programming is vice versa. i.e we only write the
code once => React is declarative.

Therefore reasons for choosing react:-


1) above reason
2) component based ,i.e. ek hi type ka code bar-bar
nhi likhna.
3) single page application -> i.e. prevents reloading
when going from one page to another of the same
website.

React is a js library -> so for importing it we can use


cdn link of react. and add the link within the script tag.
=> with react we also need to import react-dom library.
=> and inside script tag we need to mention type=text/babel;

react-dom wali link jo include ki hai above along with react,


vo apne react ke program ko browser se
communicate karwane ke liye use hoti hai.

React.createElement returns a object => for creation


React.createElement('tag_name','{ props=> this will be
storing key:value pairs and will be set as the
attributes of the tag}','content to be displayed'(or child elements));

we need to create root by defining a div in the html


file and giving it the id name as root,and then get it
inside js file

inside react.createElement we cannot set


the style ->
we need to create object for it => style:{{key:value}} (in the props)

=> behind the scene root.render(...) method of react->


is creating a dom element and then apending it into the
browser on the location which we gave inside root.

and in case of image => iska koi child element nhi hoga,i.e
blank chodna hai.

In order to prevent such long writing of react.createEle...


we can prevent it by jsx where we can write exactly
in html and we have to introduce a compiler in b/w
called babble which will take this html-like code and
convert it into the browser understandable js code .

Babel:-
using babel's cdn link is not advisable so use other
method => instead cli method is preferred.

by-default type withing the script tag is


type=text/javascipt - if something instead of this
is included than javascipt ki file request hi nhi
karegi browser par , so error nhi aega.

if we need to write js inside jsx then we need to write


the js inside curly brackets {}.

return value of console.log() is undefined, and the


values such as true,false,undefined,null are not
shown by react on the browser page.

jsx=> sort of writing html inside js.

npm init -y is a convenient way to create


a package.json file with default settings,
saving you time during the initial setup of

your Node.js project.

for setting up babel:


1) npm init -y in terminal
2) copy the cli link of babel
3) add build key-value into package.json inside script
where it will take js files from scr folder and put
them into lib .
4) npm run build in terminal.
5) include something in .babelrc which is config
file of babel (stack-overflow)
6) include some dev dependency=> npm i @babel/something -D

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

Source Maps : used for debugging


For getting it inside build in package.json extend the
build value as -> --source-maps , second method=>
inside .babelrc file include key as "source-map" and
value as true; => if this is used then this file
if used for converting the jsx code to js. // and
also helps in underestanding our code.

Flow=> apna jsx code lib folder ke script.js me


jaega then convert into js code , and then send to our
browser.

For automatic compilation to take place=> inside


build include --watch.(not again again writing npm run build).

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

Above was more of a theory wala part.

Above was all the back story , now we'll do everything with
parcel;

Parcel- it is a bundler.
for including it we need to install react and react-dom
as dependencies-> npm i react react-dom

our node_modules is not understandable by the browser,and


react client-side library hai,to apanko chalwana hai isko
browser par -> therefore we use parcel.

for installing parcel->


1) npm install .......(from parcel documentation)......
2) it already have babel as its dependency ,so it will
automatically convert jsx to js.

for using :
1) npx parcel index.html(entry point);->ye apna khud ka
server ON kar dega -> parcel is a build-tool/bundeler.

(ctrl+u=> view page source)

for uninstalling=> npm un react (un is used instead of i)

parcel does hot reloading or hmr -> i.e. without


realoading the window it does changes in the browser.

internally parcel creates it's own html and js files and


serves them by including all the necessary code and
serves it's own html file instead of ours.

The actual representation of the browser page where the


things are seen and elements get rendered is called DOM.

=> Project Creation :-


1) npm init -y => creation of new project
2) npm i react react-dom
3) npm script for downloading parcel
4) npx parcel index.html(source file name)

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

* We can pass multiple elements using an array , like we have similar


elements so we can add those many times that element in a array and pass
that array inside the root.render(arr) method.

*** problem with jsx => the order of argument need to passed
carefully .

// React-Component => is a function that returns JSX // technical defination

Solution :-

1) object destructing =>


const {key,title,image,brand,price}=cardetails -> card details is
actually a object containing key value pairs and those values
will be destructed inside the function.

2) React component= it is a react element who's type is function


and that function should be renderning a jsx that is a react element.
Therefore; while rendering pass the object and make the object's
one the key named 'type' a function_name which it will execute
while rendering. and give the parameter of the function inside
the key named 'prop' in the form of an object.
eg. root.render({
$$typeof : Symbol.for('react.element'),
type: Card, // function's first letter is capital ..
ref: null,
props:{} }); // these are the necessary key:value
pairs of this object and this is only the so called
" React-Component " .
/// or ///
---------------------

** instead of writing this all by ourself write :-


=> root.render(React.createElement(function_name,{props}))

/// or /// ( Shortest way of creating React-Component )


---------------------
** instead of writing this all by ourself write :-

=> root.render(< Card title="abc" price="123"/>)


// write the function name inside the </> and then pass props
like passing attributes in html.

---------------------
We can also check our code on jsx compiler from babel website whos
link is present on react website.

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

Component = reusable piece of content(or UI)

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

In case of images in order to make image component , we need to


import the address of the image and then pass the name of the
image in {img_name}.

And we need to pass props also like this => {property_name,...}

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

Event-Handling in React.js

Apan component ke upar onclick wagera nahi laga sakte , instead we can
apply events directly on tags -> like onClick,onMouseover,....

We can pass functions while calling component but they will


be passed as props to the components where they were declared
and we can use them directly.

React fragment=> <> </> => jab ye likhte hai tab koi bhi element
create nhi hota hai , used at times when we need to return
multiple elements and we want to enclose them.

And jab style dena rehta hai then curly brackets ke andar ek
object banakar dena => eg. { { color:"red" , ... , ... } }

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

For Re-Rendering of a component without using states =>


call the root.render(< fn_name_to_be_re-rendered />) method.

And for this we need to define root and createroot method in this
file also , so we need to copy-paste that 2 lines from script.js
file to this file also. // or // we can pass root as props

// but above are not good way of re-rendering therefore we


should use states.

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

State :-
for using state we will be using a fun. named as useState() -> also
known as useState hook -> hooks are just a fancy name for functions
that give some extra functionality.

const [count,setCount] = useState(1)


-> basically useState returns a array of 2 things :
1) intial value , 2) a function for updating the value
-> count represents the starting/initial value or useState[0]
-> setCount represents the function for updating the function or
useState[1] .

Whenever useState is called the component gets re-redered if the new


value is different from the intial value , if it is similar
to intial one then it won't re-render bcz. internally it understands.
-> and reason behind how it is remember the old value is that
internally it is using the concept of "closures".

=> first pass = {count}


=> then pass = {setCount(count+1)}

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

In case of js we need to write code to update the variable ,


then we also need to write the code to update the DOM , but in
case of React we only need to code for updating the variable ,
DOM ko update react khud kar lega.

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

BTS working of useState :-

=> when we call the setCount(count+1) function then it will not


re-render until and unless the complete call-back function gets
over , and internally it stores the intial and the new values
in a array , and therefore if we write (setCountcount+1) function
2-3 times again one after other then also it will update only
once

=> and if we want to update as many times as we call then


do -> setCount((prevCount)=>{return prevCount+1}) , i.e. provide a
call back inside the setCount and here react itself will update
the count immidiately.

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

# State vs Props :

*State: it always remains inside the component and it is mutable i.e


changeable in nature and whenever a state changes it's value then
our component gets re-rendered . It is used in cases where a
variable needs to change it's value again and again.
*Props: these are non-mutable that is it will not be changed , (we
can change the value of prop , but it is bad practice in react)
props are only used when we want to pass values .

*Props and state can also be used together , for eg. we can pass
props and it can be used as the intial value of a state.

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

React Fragments :
1) either import {Fragment} from 'react';then <Fragment>..</Fragment>
2) or simply set empty brackets => <>....</>

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

Children Prop Uses :


1st use) saves us from writing one prop , as it could be directly passed
into the body or it can be passed as prop with key as 'children'.

for eg.) a component like this <Basket /> can also be written as
=> <Basket>...some_content...<Basket/> => now this middle content
can be anything , but if is js then write it within {...} , and
the some_content gives a extra prop where the component is declared
and the prop name is 'children' .

2nd use => we can pass one component into another component and then we'll
render that passed component using children , as we can access it using the
children prop and simply render it by writing
b/w curly bracket => {children}

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

Conditional-Rendering :-
=> If a particular condition is met then only reder a particular element
else do-not render. => for eg.) <p> {apple_count===10 ?'full':'not'}</p>
=> above eg.is done using ternary operator.

Apne DOM me false,true,NULL, wagera nhi dikhta ,therefore it can be


used for putting conditions like above =>
<p>{apple_count===10 && 'full'}</p> => this
means if count will be 10 then 'full' will be displayed else it won't be.

Apan pure component ko bhi conditionaly render kar sakte hai , by putting
some booleans value.

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

CSS in React :

if CSS is loaded only once on our page then also , if on a particular


class a css-property is applied on some other files component having
the same class-name on that also this css-property is applied , even =>if
we have not imported that css file and => also if it not part of react.

To prevent it we use CSS-modules :-


=> Steps
1) make the file extension as file_name.module.css instead of just '.css'
2) import like this => import styles from './file_name.module.css'

3) and if in css file we have applied property on 'button' class-> then


we need to apply className as {styles.button} instead of only button.

=> And if the name is like abc-def then we cannot do styles.name , instead
we have to do styles[abc-def] (i.e. jab hypen laga ho).

=> And if multiple class have to be applied =>


className= { [styles.button , styles.textX].join(' ') }

4) Reason for its working => it is working bcz. the parcel creates it's
own css file and gives a key/modifier for the identification of the
class-name which we have given.

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

Project-I

= We can use = HTML to JSX converter , when we want to convert


html to jsx.
= create separate components for all .
= for iterating to different elements = we will
use map function of js.
----------
search functionality is given by useState hook and
using the concept of lifting up the state => means
passing the state from one component to anotber.

Lifting Up the state = this means jo state hai usko


parent component ke upar leke jana hota hai.
-----------
UseEffect uses: its first argument is call-back funct.

1) ** if we want to run a particular thing only once


then we can use useEffect and for that we have to pass
an empty array as second argument.Second empty array
is actually dependency-list . And agar uss array me
kuch pass karenge then , agar vo particular chiz
change hogi then hi re-render hoga otherwise nhi hoga.

2) it is basically used for monitoring the state.

3) also used for unmounting .In case of rounting it


happens automatically , but manually also we can do it
with the help of useEffect.
=> in case of setInterval
even upon unmounting , it is being saved in the
memory and continues to run , so for that case clean-up
is done to stop it.
--------
Baar-baar render na ho that why we are using useEffect.
Eg. when we use fetch for getting all the data and put
it inside setData() => then infinite request would
occur.
---------

React Rounter V6 :
For routing in react we need to use a different library
other than react called react-router for rounting
to different pages. bcz. by default react only supports
only single html page customised by the parcel package.

Now using the above = we will have the flexibility


of routing to different components at different routes
that is inside the "createBrowserRouter"=> we need to
specify the route and corresponding to it which
component to render.

1) Inside the root.render method we can write the


routerProvider component where the components
will be changing and the components that would be
same accross all the pages can be mentioned as it
is inside the root.render method.

2) more better way than above => using children key


which accepts any array of objects
of path and element => in which we need to give
after the parent path on which child path which
component should be rendered. => ** And for this
we need to give <Outlet/> component provided by the
react-router inside the parent comonents file. And the
common components can also be added there itself.

-----------------------
For Error handling : pass key as "errorElement" and
value as "our own error component". => useRouteError()
is a hook which is used to identify the type of error
and does not contain any parameter.

so inside our error component=>


const error = useRouteError();
console.log(error);
-------------------------
For iterating over an object use => Object.values()
-------------
For fetching any api =use useEffect hook
--------------
* To avoid re-loading : reloading happens bcz. for
routing that is going from one page to another we are
using <a> tag . => So to prevent re-loading use =>
<Link className="_._._" to="link" > <Link/>

instead of anchor tag use Link tag and instead of


href attribute use =>

=> the above link property is provided by


react-rounter-dom.

Actual feature of react-router-dom = without reloading


routing to different pages.
---------------------------------

* And another way of infinite routing is that , inside


createBrowserRouter=> inside one of the path add ":",
so whenever a new undefined route is being called it
will be redirected to the one have the path with ":"
eg. path: "/:country" .

+++

useParams() is hook provided by react-router-dom


that gives the access to the route along with it's
value to us , which helps in dynamic routing. =>
eg. using it inside the component defination =>
const params=useParams();
// console.log(params)
+ inside the CountryDetail component= we are accessing
country name using URLSearchParams -> so instead
use useParams() to access .
eg. const params=useParams();
console.log(params.country)
+
we also have to make changes in the href attributes
since now we are not going to longer links , therefore
we need to make it shorter by providing only
country_name.
-----------------------------------------
Try to handle error using "catch" with fetch.

For back button add a event "history.back()" to go to


previous page.

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

To avoid multiple re-renders we can use promise.all,


here we can store all the promises in an array and
apply promise.all on that array, so it will render
only once .
------------------

** For applying "sheemer effect" -> create a separate


sheemer component and give the exact same css to
it as given to the cards of there place
and then apply conditional in order to display them
only when nothing is there to render on the screen.

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

For getting a array with default values in array =>


* const arr= Array.from({length:10}).map((e)=>
return 'Anurag'}).

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

Passing Data from one place to another in React :


if we have already fetched the data of something on
one page and then if we require that on another page
then why should we fetch that again , we can pass
that from previous page to current page.

We can pass the data from the one page =using the link
tag (inside that we need to pass "state" as key and
the value as the data which we want to pass),
and then accept the data on the other page using
the useLocation() hook provided be react-router-dom.

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

If in case something is not getting fetched fast and because of


that error is occuring , then use setTimeOut(pass_callback_func)
and no need to pass the time , by default it will take 1 sec.

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

for dark mode we will use useLocation hook provided be react-routend


and also do not do simply dom manupulation , instead pass props
and do the operationn with the use of diff. hooks.

How to pass props inside "outlet" => using the attribite


' context={inside this array needs to be passed} ' // we can pass this context to
any
component that is begin rendered through the Outlet Component.

=> useOutletContext() is a hook which can fetch the array which


is passed as prop from the parent component. It is only applicable
when parent is Outlet , this means all those components that
are being rederend through outlet component can access the
props given with the key name="context" and this will contain
an array.

Basically context is used to prevent prop-drilling from parent


to child when there is a huge hirarchy.
So above was the context provided by the react , but we can define
our custom as well and define what all need to be passed
and we can directly import it .

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

For creating a context of our own we need to create a new js file


and them import createContext from react , then
export const ThemeContext = createContext(inside this we can
pass default value);

and for accessing it we need to import in another file :


import {ThemeContext } from './-----'
const [theme] = useContext(ThemeContext);
// useContext is another hook used for using custom context.
// here inside theme we will get default value

or we have can wrap our components with contextProvider eg.


// ye wrapping App.jsx ke andar karna hai aur value me array me multiple value
de dena
<ThemeContext.Provider value={[isDark,setIsDark]} > // inside the value attribute
<Header />
<Outlet />
</ ThemeContext.Provider>

// here we are not required to pass anything inside outlet or


header components.

*** or // another way = apan pura logic themeContext me bhi rakh sakte hai

*** ek ThemeProvider naam ka function banao context file me containing the state's
which we need to pass ,
then wrap the components in app.jsx in to the ThemeProvider tags ,
then the components will become children of ThemeProvider , so
inside the context file -> inside the ThemeProvider function ,

---------------------------------------------------
** Custom Hooks : these are nothing but normal functions that we create
in a separate file inside which we can use any other hooks , and after
creation we use them in multiple other files where it is required.

If we have created a functionality on one page , to get that on


another page , we have to copy-paste the same on another page,
so to avoid that we can create a separate file with the
extension as jsx or js and then we can import that in other files
thus making it reusable.

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

* Filter funcitonality is provided by the setQuery state of the


useState hook only using lifting up states concept.

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

For deploying we need to run the build command and also we need
to add a - " build : parcel build index.html " in package.json

and we need to remove " main : index.js " line from package.json .

End of Project-I .
---------------------------------------

Forms in React:
In Expense Tracker = we will be using vite , for lightning fast development.
-> it is much faster than parcel.

=> eslintrc is used to find errors while development that comes together with vite.
=> crypto.randomUUID() -> generates unique id.

** select ke upar "name" attribute hona chahiye -> tabhi form se data extract ho
sakta hai , with the help of " const data=new FormData(e.target)
for(const [key,value] of data.entries())
{ console.log(key,value); } " // we need to loop
over it using
for-loop to get
there values.

// data.entries se both key and value mill jaegi , then we can de-structure them
in order to get them.

When we use map then we need to give the key inside the element which we passed
inside the map.

** For reseting the form after submission of one entry - " e.target.reset() "

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

Controlled Components :-
**( // instead of the above method of FormData() we can use below method of
controlled inputs to get the form data. )

One way data binding // or // uni-directional data flow => in this our UI will
only change when there will be change in data => i.e. change in data will
change the UI(dom) , but change in UI can't change the data(which is the case with
2-way data binding ).
=> And using this only we will create "controlled inputs" ->
as in this case our input is controlled by our state-value.

Here we will create "state" for the each field and then set the 'value' attribute
in the select or input field of the required-field and we also need to set
"onChange" event where we need to set the setState function and give e.target.value
inside the setState.
** (If we don't give onChange event then we won't be
able to write anything inside the input-field on the screen as it's a default
property of React.js )

And in the above case e.target.reset() won't work in case of one-way-data-binding


instead we have to update the setState('') as empty for all the fields.

** We can also combine all the changeing field states into one by forming
only one state and storing all the values inside that as object state and updating
it
accordingly.

** While spreading the prevState use the spread method - enclose the prevState
and current-object in an array => eg.
setExpense((prevState)=>([...prevState,expense]))

------
// in order to prevent writing the onChange event in all the elements ,we can
create
a function and pass the "name" attribute to uniquely idetify the elements.

-> if we need to pass the attribute name dynamically inside a function then first
destructure
it , then pass it inside square-brackets, so that if it's field changes then it's
corresponding value also changes.

----------------------------------
// Upar wala method is good to use , but we should know useRef method also.

=> " useRef Hook "= this return a object having a key-> "current" and it have value
which
we have given to it -> const myRef= useRef('rishi') => so the object's current
key will
have value='rishi'.

// another method of getting the input is -> using useRef() hook .

** Reason for using useRef:-


1) it does not show updated value on DOM,until and unless re-reder takes place. And
it does'nt
re-render also, i.e. it saves it updated value within itself and whenever re-
render
happens due to something (like setState ) then it display's it's updated value
on DOM.
2) We have a prop named props -> if we use that inside any of element then we can
refrence
out useRef to that element and after that we have the power to change it's
properties.

for eg. const myRef=useRef(0) // intially 0 hogi value,then myRef will refer
to "select"
<select props={myRef}> something_something </ select>

=> now bcz. of this we can set properties on select using myRef .
=> eg. myRef.current.style.backgroundColor='red' or
=> eg. title:myRef.current.value // jo type karenge title field me vo
title me
store ho jaega.
------------------------------------------------

** Adding validations to Form in React.js

=> If we call a function having useState inside it from some another function, then
it won't
run the useState until and unless the entire parent function is complete , after
completion only
the called function's useState will be executed.
--> ** So instead what we can do is - we can return that state value after using
useState as
it will update the state value and we will get the updated value of the state.

=> to convert a object to array => Object.keys(object_name) => so using this we can
use the
"length" function of the array in order to find whether it contains any items or
not.
-----------------------------------------

** Advance Validation -> " using Custom Form Fields "

-> Custom Form Fields are nothing but making the fields re-usable by creating them
into separate
components in another file , and passing the contents as props in order to pass
different values.

// Watch again for more understanding ..

=> For advance validation => create a object named validateConfig containing key's
as the
name of the fields on which the validation needs to be applied and there value
should be
an array -> array can we have mutilple validations for a single field like ,
not-null ,
short-length , etc. And inside that error also we have to pass objects only ,
containing
key-value pairs .
=> For email verification -> use regex which will check for proper email extension
of the
user input.

=> And now in the final part -> for applying the validation we'll use the
".forEach" method and
inside that we will be using ".some" method (it is used with return true , it
should be
used bcz. it doesn't go for next iterations once it gets a value) for iterating
over each
object value of the validation object.

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

** Filtering Data - Using Custom Hooks:


Just apply .filter method over the input array and store that into a variable and
use that
variable to map and iterate over the values to be renderd on the DOM . Also
create a hook
in order to store the updated value and render them.
=> In order to make this filter-functionality reusable - create a separate hook
for it ,
and use it where-ever we want to apply filter functionality.

** Hooks ko simple export karte hai - i.e. default keyword nhi lagana rehta.

Steps for custom hooks:


1) first create a seprate hooks folder and create a useFilter.js file.
2) then create a named export function with parameter as -> (data,callback_func)
3) this call-back function will be used to set the field on the basis of which
filtering should take place.
4) Now in the new file inside the filter function , create a [query,setQuery] hook,
the filtering will be based on query, and the updation using setQuery will take
place in the original file, so we need to return [filteredData , setQuery].
5) the callback function will be like -> ((data)=>data.category) , in place of
category we can replace it with field based on which filtering should take
place.

Watch again...
-----------------------------

** For totaling the value of the expenses => use ".reduce()" method of js , and
apply
that on the filtered-data and in this give the "starting value as 0" .

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

** Custom Context Menu : Jab right click karte hai to jo options aate hai( like
copy-text,
save,copy-link) use context-menu kahte hai. We can also create custom context-
menu using
react.

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

Sorting in js. => arr_name.sort((a,b)=>a-b) ->in ascending order,and (b-a) in


descen. order
In this case of sort it will return the same array , so re-render won't occur ,
so using the spread operator , return the previous State and also perform sorting .
eg. setExpenses((prevState)=>[...prevState.sort((a,b)=>a.amount-b.amount)]

in case of object with multiple key-value pairs=> then apply sort on


which key we want to apply sorting-> like " arr.sort((a,b)=>a.amount-b.amount) "

sort based on prevState .


to stop re-rendering due to another setState->
onClick((e)=>{ e.stopPropogation .........})
=> using e.stopPropogation we can stop other re-rendering due to other states, and
can focus on our present state only.

Another way of stoping -> if we have done a setState for closing the
context-menu then we can make a check that only if there is a left-or-top
value with us due to clicking of context-menu , then only re-render else
don't do anything , and this will prevent un-necessary re-rendering of
our components.

** Another method of sorting which gives us more freedom and helps us


to clear the sort also ->
1) create a use state for the callback from the sort function:
const [sortCallback,setSortCallback]=useState(()=>()=>{})
-> Don't get confused this is the correct method using which
we can control the array.

2) for getting the array in the same state as initial=>


setSortCallback(()=>()=>{})

3) for getting in ascending order ->


setSortCallback(()=>setSortCallback(()=>(a,b)=>a.amount-b.amount))
Watch again for more clarity.

And also we need to set this setSortCallback with our filteredData.map=>


eg. filteredData.sort(sortCallback).map ........

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

You might also like