0% found this document useful (0 votes)
4 views12 pages

JavaScript, React, and JSX Fundamentals

Uploaded by

Yash
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

JavaScript, React, and JSX Fundamentals

Uploaded by

Yash
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#--------------------------Day 1----------------------------#

#JS
-JavaScript is loosely typed laguage
e.g. a=10
b="Aditya"
Webpage/Document---->treated as object
-JS interprets Object and it treat HTML file as Object
-Object is feature of JS
-DOM is at frontend and not at Backend
-DOM is a tree like structure
-HTML---->referred as document
-HTML converted into DOM and that is treated as Object and then JS handles that
object
-HTML files contains spaces these spaces are also present in nodes of DOM tree
-JS has "document" named variable and it holds HTML file as Object in the form
of DOM
-DOM is handled By Browser
-DOM is Not feature of JS but it is feature of Browser
-JS only uses DOM for Manipulation Purpose

#--------------------------Day 2----------------------------#

#Library vs Framework
-Framework provides readymade things but less flexibility
-Library provides less readymade things but more flexibility
-Library subset of Framework
-Library provides inbuilt implementation of functions
--Library-->
-Collection of Reusable code.
-Not need to write repetitive/complex code.
-No boundaries for development
--Framework-->
-Predefined architectural pattern
-The development needs to be done in limitations enforced.
-Boundaries for development

#React
-Composable/Declarative

#Node
-It is runtime environment
-It creates runtime env for JS code execution.
-Chrome contains V8 Engine which analyze JS code and displays frontend.
-At frontend Browser executes JS code and at Backend NodeJS executes JS code.
-NodeJS allows to execute JS code outside the Browser. which was not possible
but it is now.
Eg. at terminal type node and which allows to write JS code

#npm(node package manager)


-It manages dependencies
-Handles recursive dependencies efficiently on behalf of us.

#Project Files
-JSON-JavaScript Object Notation
-JSON contains object in the form of Key-Value pair enclosed by curly braces.
-[Link] --> contains the details of dependencies on which project depends
on
-node_modules Folder-->this folder stores all the dependencies of the
[Link] of
this folder is highest in the project.
-[Link]-->version locking

#Project Modes
-Production mode
-Development mode

#npm intall
-command downloads all the dependencies specified in [Link] in the
"dependencies" key.

#.js vs .jsx
-.js is for plain JavaScript file
-.jsx is for react code.
-In .jsx file JS code can be mixed with HTML code i.e. we can write JS with
HTML.

#createRoot function in React


-render() method accepts only one element as parameter
-if you don't want multiple div then take empty fragment <></>
-Empty fragment not displayed in element when inspected in browser and if div
is taken
it is displayed.

#render() in-depth
.render(
<h1>Hello</h1>
<p>World</p>
)
-above syntex in JSX not allowed because render method only accepts only one
element as a parameter
-solution to above problem is to take single div and put h1,p in that div as
follows
.render(
<div>
<h1>Hello</h1>
<p>World</p>
</div>
)

#[Link] render() not takes multiple element as input paramter?


-By using createElement method in react' pkg we can able to create and element
in react
without using JSX.
E.g.
1).render(
<h1>Hello</h1>
)
-Create Element will take below syntax for above code
-const element=createElement("h1",null,Hello)
2).render(
<h1><span>Hello</span></h1>
)
-Create Element will take below syntax for above code
-const element=createElement("h1",null,createElement("span",null,"Hello"))
-means here createElement method on crunched within another createElement
method and it
is possible because this syntax is allowed by JSX
3).render(
<h1>Hello</h1>
<p>World</p>
)
-Create Element will take below syntax for above code.
-As two HTML tags are below each other so we need to take two
createElement() methods
below one another.
-const
element=createElement("h1",null,"Hello")createElement("p",null,"World")
-But above syntax of createElement() is invalid in JavaScript.

-->Therefore only one element is allowed in .render() method.

##Project Creation by using vite


1)React_Folder>npm create vite@latest
-vite can be used in any Framework(select Framework as React).
-select variant as JavaScript.
2)cd <Project_Name>
-project specific command execution.
a)npm install (creates node_modules folder)
b)npm run dev (runs the react project)

#Babel
-Babel is a JavaScript compiler.
-As browser only understands JavaScript the babel converts react into JS
because babel able convert react to JS.

#Componet
-Can be called from anywhere from the project and can be used in anywhere in
the
project.
-It is nothing but function.
-Function name and Component name should be same.
-Component name should always start with capital letter.
eg.
[Link] -->Component
--[Link] contains below function
function App(){
return(/*Write JSX here which is to be rendered*/)
}

#createRoot().render() -->this is compounding


-above code is replacement for below code
const root=createRoot()
[Link]()
-eliminates extra variable requirement

#--------------------------Day 3----------------------------#

[Link] to write react code in .jsx not in .js?


-React code can be written in .js file also but most of the Framework won't
support this
so it is problematic
-It is strongly recommended use .jsx file for react code.
-Files present in public folder of project are not processed by Babel compiler.
-createElement() is alternative to JSX and vice versa.

-----Introduction to JSX and Babel-----


-JSX -->JavaScript XML
-JSX is an extension of the JavaScript language based on ES6(ECMAScript 6)
standard.
Standard is an protocol follwed by everyone.
E.g. To manufacture PD every vendor should make it of same Size.
-JSX allows to write HTML directly within JS code.
-JSX makes it easier to add and write HTML into JavaScript.
-When application is run,JSX is "transpiled" into JavaScript code and then
execution done as per
JavaScript code.

-Transpilation---->
-Consider following JSX code
[Link](
<>
<h1><span>Hello</span></h1>
</>
)

-above code is converted into


-const element=createElement("h1",null,createElement("span",null,"Hello"))
-Means JSX containing HTML+JS is totally converted into pure JavaScript.
-This is transpilation.

[Link] is JSX?
-JSX allows us to write HTML elements in JavaScript and place them in the DOM
without any createElement()
and/or appendChild() method.
-You are not required to use JSX, but JSX makes it easier to write React
applications.

###Rules for using JSX includes:


-Return a single root element
-Close all tags
-Use camelCase for most things.
-Don't use class keyword as class name.
-Don't put quotes arround curly braces when embedding a JavaScript
expression in an attribute.

###Babel
-It is transpiler.
-Babel is a toolchain that mainly used to convert ECMAScript 2015+ code
into a backword compatible
version of JavaScript in current and older browser or environment.

###Webpack
-Bundles all JavaScript files from Project which makes single binary file
which is
understandable by [Link] is bundled file uploaded to [Link]
process reduces
the size of project.
-It is a free and open-source module bundler for JavaScript applications.
-It is made primarily for JavaScript, but it can transform frontend assets
such HTML,CSS and images
if the corresponding loaders are included.
-It is static module [Link] means that it takes JavaScript codes and
all of dependencies
and convert that all files into single files.
E.g.
-CSS file contains much spaces for human understanding but webpack
removes that spaces and
result in reduction in file size.
-Means file is compressed but it is very hard to understand to human
but it easy for machine to
understand.
-This is compression file means.

#JavaScript inside in JSX(HTML)


-In order to embed JavaScript expression inside JSX it should be enclosed in
curly braces{} in HTML code.

#--------------------------Day 4----------------------------#
##Inline Styling for React elements-->

#Normal CSS
function App(){
return(
<h1 style="color:red">Hello</h1>
);
}
-Above code gives error in React because styling in React is not specified as
string value to
style attribute.
-Instead need to create JS object for styling and need to pass that object to
style attribute.

#Below code shows Styling in React


function App(){

let obj={
color:red; //CSS in the form of Object
}

[Link]=white; //by using obj access css properties

return(
<h1 style={obj}>Hello</h1> //{obj} -->object passing to style attr.
as code is JSX.
);
}

#Below code shows Styling in React using compounding


function App(){
return(
<h1 style={{color:red}}>Hello</h1> //{{}} -->directly css written
within inner curly
);
}

-In React CSS property names are always written in camelCase because CSS
written in
JavaScript object and object contains key:value.
eg. font-size--->fontSize

##Component creation in React----->


-Component is nothing but file with .jsx extension.
-It is recommended that to create components and call those in "App" component.
-Project is divided into multiple sub-components.
-For creating component just create .jsx file.
Eg.
-Now we are creating [Link] containing Heading wrapped in h1 tag and
[Link] containing
list of programming languages.

-------------------------------------------
[Link]
function Heading(){
return(
<h1>Programming Languages</h1>
);
}
export default Heading
-------------------------------------------
[Link]
function List(){
return(
<ul>
<li>C</li>
<li>C++</li>
<li>Java</li>
</ul>
);
}
export default List
-------------------------------------------
[Link]
import Heading from "./Heading"
import List from './[Link]'

function App() {
return (
<>
<Heading />
<List />
</>
)
}
export default App
-------------------------------------------

###JavaScript ES6 import,export node_modules

#Types of export
1)default export
- we can change name of imported variable/function after import
keyword.
Eg.
-----------------------
[Link]
const pi=3.1415;
export default pi
-----------------------
[Link]
import PI from './math' //PI and pi are diff names for same
var

function App(){
return(
<h1>Value of PI={PI}</h1>
)
}
-----------------------

2)named export
-By name it is exported.
-At the time of importing name of exported cannot be changed.
-Name of variable at exporting should be same as name of variable at
importing.
-Curly braces are used for import and export.
Eg.
-----------------------
[Link]
const pi=3.1415;
export { pi }
-----------------------
[Link]
import { pi } from './math'

function App(){
return(
<h1>Value of PI={pi}</h1>
)
}
export default App;
-----------------------

##Default export is not compulsary.


##A file contains only one "default export" and as many named export.
##Important variable/function is exported by using "default export".
##For remaining "named export" is used.

##export default and named default compounding


-----------------------
[Link]
export default const pi=3.1415;
export function math(){
return 2*pi;
}
-----------------------

##Exporting multiple named defaults


-during export multiple named exports are taken into curly braces and
separated by comma,
while during importing same process followed.
Eg.
export { var1,var2 }
import { var1,var2 }

##if functions are exported by using "named exports"


and imported as { fun1,fun2 } then while calling those functions use round
brackets as {fun1()}.

##imperative Approach
-Just tell "What should be done" and along with "how it should be done".
Eg.
---------------------------------------------------
[Link]
const heading=[Link]("h1")
[Link]="Hello World"
[Link]="heading"
[Link]("root").render(heading)
---------------------------------------------------
-All instructions need to mention

##Declarative Approach
-Just tell "What should be done" and no need to take care "how it should be
done".
Eg.
---------------------------------------------------
[Link]
const root=createRoot([Link]("root"))
[Link](
<h1>Hello</h1>
)
---------------------------------------------------
-render method will responsible for content rendering no need to
specify how to render it.

##React props<---->Reusable Components


-Component takes different data as input and renders the data, passed data to
component is props.
-Whatever which is not a part of JSX but want to use in JSX simple make use of {}
curly braces.
-Props refers to the properties being passed into a component in order for it to
work correctly, similar to
how a function receives parameters.
-A component receiving props is not allowed to modify those [Link] are
immutable.

#[Link] props are immutable?


--> -Props being send from "Parent to child"/"calling to componets" those won't be
modify because it may result in
un-expected outputs.

#--------------------------Day 5----------------------------#

#--------------------------Day 6----------------------------#
--foreach()--->iterate array but does not return it.
--map(first_object,index)-->iterate array but return it.

#&& in JS
#Ternary Operator
#Conditional Rendering

#--------------------------Day 7----------------------------#

##Array and Object Destructuring


##State in react
--Value of variable at particular instannce is called state.
--UI=f(state) -->Mathematically UI becomes function of state
##Hooks
--These are the readymade functions which are used to manage states of react
project.
--It attaches UI to a state therefore it is called Hook.

##useState Hook

----Consider------
function App() {
[Link]("Comopnent Rendered")
let count=0;

function increament(){
count=count+1;
[Link](count);
}

return (
<>
<h1>{count}</h1>
<button onClick={increament}>+</button>
</>
)
}
--Here App component is rendered only once when it is called.
--So here when component get rendered "[Link]("Comopnent Rendered")" this
line
executed only one time and can be verified on console.
--So, as initially count is 0 at the time of first time rendering value
displayed is 0;
--When we clicked on button it increament the value of count by one but it not
get rendered
on the UI.
--Means on updation of count variable the App component should get re-rendered,
so useState() hook is helpful to do this.
--while calling increament function on clicking button
onClick={increament}---->this calls the function after actual clicking on
button.
onClick={increament()}---->this calls the function at the time of App
component rendering.

##const state=useState(); --->const [var,setVar]=useState(0)


[Link](state) ---> [undefined,f]
--useState() return array of two elements, first element is variable and second one
is function which is anonymous
--const [var_name,setVar_name]=useState(initial_value_of_var) --->array
Destructuring
-Here var_name gets initial value that which passed to useState.
-And setVar_name is a function which used to manipulate that variable.
-After Manipulation of variable by that function the useState re-renders the whole
component again.

##setInterval(function_name,interval-in-ms) method in react


--this method executes a certain function after specified time interval.

#--------------------------Day 8----------------------------#
##React forms and Event Handling
#--------------------------Day 9----------------------------#
##Data Fetch and useEffect Hook

-JSON file follows convention of JS object therefore file named as JSON.


-<pre></pre> -->this tag is useful to show code/program on UI.
-rfc-->React functional Component.
-rafc-->React Arrow functional Component.

-[Link]()---->method converts the JavaScript object into JSON format consist


of String.
let obj={
name:"Aditya" ----->object
}
-[Link]([Link](obj));
-[Link](obj);
{"name":"Aditya"}----->both key and value are in Strings after stringfy
{ name: 'Aditya' }----->Orginal Objects

##Fetch data from API using fetch() method---->


-fetch("URL from which data to be fetch").then()...
--Means by when data from fetch() is fetched then we need to execute promises.

##fetch() Demo--->
function App() {

const [dataFetch,setDataFetch]=useState(null);

fetch("[Link]
.then(data => [Link]())
.then(data=>setDataFetch(data));

[Link]("Component Rendered")

return (
<>
<pre>{[Link](dataFetch,null,2)}</pre>
</>
)
}

-Consider above code snippet


Steps:
1]Initially Component called and App() function starts execution
2]state variable "dataFetch" get initialized with NULL value.
3]fetch() function takes an url paramter and send request for data
fetching...
as fetch() taking more time for data fetching, so the code below starts
executing.
when data is received by fetch() the promise will respposible to pass
that data to rest of the
code.
-Means fetch() function runs asynchronously
4]"Component Rendered" printed on the console.
5]The <pre></pre> tag executed with "null" [Link] data available to
fetch() method it sets the
"dataFetch" [Link] data displayed on the the web page.
6]As "dataFetch" variable is changed the component rendered again.
Component re-rendering means App() function executes again.
7]This is how code executes for infinite [Link] again same as from
Step-1.

--This Infinite loop may create complications.


-->Therefore solution to this problem is useEffect() Hook.

-React has control over the hooks.


-Elements on which react has no control are called side [Link]. URL
-So to solve this issue useEffect() is used in react.

##useEffect(function(){},[_Dependency_Array_])
--Hook ensures that the code within useState() hook will execute once at first time
of component rendering
when _Dependency_Array_ is empty.
--First parameter to useState() contains [Link] Elements on which react has
no control are crunched
within that function .Eg. fetch()
--Second parameter is _Dependency_Array_ containing list of variables, which on
change the useEffect executes.

function App() {

const [dataFetch,setDataFetch]=useState(null);
const [count,setCount]=useState(1);

function increament(){
setCount(prevCount=>prevCount+1);
}

useEffect(()=>{
fetch(`[Link]
.then(data => [Link]())
.then(data=>setDataFetch([Link]))},[count]);

[Link]("Component Rendered")

return (
<>
<h1>{count} </h1>
<button onClick={increament}>FetchNext</button>
<pre>{[Link](dataFetch,null,2)}</pre>
</>
)
}
export default App

1]Initially Component called and App() function starts execution


2]state variable "dataFetch" get initialized with NULL value and State variable
count also get initialized
to 1;
3]If _Dependency_Array_ array is empty then the useEffect executed only once at
the first time
rendering of App componenet, but here "count" variable is within
_Dependency_Array_, therefore
useEffect execute when there is change in variable.
4]fetch() method is executing asynchronously and below code is get executed.
5]"Component Rendered" printed on console.
6]When there is change in "count" the useEffect executes and component renders
accordingly.
##Controlled Component--->
--All the control of the component is owned by react itself.
--Initially HTML holds the [Link] attribute
--When <input type="text"> when text is entered in the input field HTML sets
the value attribute internally.

#--------------------------Day 10----------------------------#
##To-do app

##Changing the state Present in Parent component by Child component.


##When multiple times same component getting called then it should assigned with
unique "key" property.
##"key" is predefied.
##Key is not a [Link] is used by React internally.
##React state can be only changed in component in which it was defined.
Eg. -State of Parent cannot be changed by Child directly.
-Parent passes a function which is defined in parent itself to a child by
using props, then child can callback the function which
is responsible for state change.

#--------------------------Day 11----------------------------#
##React forms
<label for="" /> --> In jsx "for" attribute is replaced by "htmlFor" because "for"
is keyword in JavaScript.

#------------------------------------------------------------#
[Link] Drilling
[Link] API

-In projects it sometimes props are need to pass from Parent to it deep childs.
-So unnecessarily child of parent need to maintain and pass the data thorough props
to [Link] is called Prop drilling.
-solution to this problem is context API.
-For EX. refer project -->project-drilling

#------------------------------------------------------------#
##useRef hook---->

-If component is rendered by using strict mode then browser renders the page double
to check wheather it is working properly or not.
-->const count=useRef(0);
-returns object which contains 'current' named key and holds the passed initial
value.
-if ref changes then it won't re-renders component.
[Link] 'count' is constant above then how value changes?
-->useRef returns object and that object is constant but the key 'current' inside
it is not constant and it can be modified.

[Link] Simple variable 'var' and useRef() both does not re-renders the componet then
why useRef()?
-->simple 'var' on increament its value not persist in successive component
renerings.
-But useRef's object value is persist in successive component renerings.
-Means value of simple 'var' is resets after every componenet rendering.

You might also like