React Notes
React Notes
and in case of image => iska koi child element nhi hoga,i.e
blank chodna hai.
Babel:-
using babel's cdn link is not advisable so use other
method => instead cli method is preferred.
--------------------------------
------------------------------------
------------------------------------
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
for using :
1) npx parcel index.html(entry point);->ye apna khud ka
server ON kar dega -> parcel is a build-tool/bundeler.
----------------------
*** problem with jsx => the order of argument need to passed
carefully .
Solution :-
---------------------
We can also check our code on jsx compiler from babel website whos
link is present on react website.
---------------------
---------------------
---------------------
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,....
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" , ... , ... } }
-----------------------
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
------------------------
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.
-------------------------------------
-----------------------------------
-----------------------------------
-------------------------------
# State vs Props :
*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 => <>....</>
-----------------------------------
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.
Apan pure component ko bhi conditionaly render kar sakte hai , by putting
some booleans value.
--------------------------------
CSS in React :
=> 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).
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
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.
-----------------------
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.
+++
-----------------------------------------
------------------
------------------
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.
------------------
--------------------
---------------------------------
*** 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.
----------------------
---------------------------------
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 )
** 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'.
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.
------------------------------------------------
=> 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.
-----------------------------------------
-> 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.
=> 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.
-------------------
** Hooks ko simple export karte hai - i.e. default keyword nhi lagana rehta.
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.
--------------------------
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.
--------------------------