ReactJS Introduction
What is React
- React is a free and open-source front-end JavaScript library for building user interfaces based on components.React is a Library. It is maintained by Meta and a community of individual developers and companies. React can be used to develop single-page, mobile, or server-rendered applications with frameworks like Next.js.
Main Difference b/w Framework & Library
- The main difference between is Library takes minimum effort to put it into our code.
What is Emmet?
- Designed to speed up the process of writing and editing code by providing a set of shortcuts that can be quickly expandable to full code blocks.
Let my index.html looks like: ⮷
<head>
<title> Namaste All </title>
</head>
<body>
<div id="root">
<h1>Namaste Everyone !</h1>
</div>
</body>
To do the above coding in javascript; ⮷
<body>
<div id="root"> </div>
</body>
<script>
const heading=document.create Element("hi");
heading.innerHTML="Namaste Javascript";
const root=document.get Element By Id("root");
root.appendchild (heading);
</script>
To do the above code in ReactJS ⮷
What is CDN?
- Content Delivery Network (CDN) is a n/w of servers that delivers content to users. Both React and ReactDOM are available over a CDN.
What is Cross Origin attribute ?
- [CORS (Cross Origin Resource Sharing) is an HTTP header based mechanism that allows a Server to indicate any cross origins (domain, Scheme or port) other than it's own from which a browser should permit loading resources.]
- CA):- Cross Origin attribute provide support for CORS If we serve React from a CDN, keep crossing in attribute Set.
<script cross origin src=".."> </script>
index.html
<body>
<div id="root"> </div>
<script cross origin
src="https://...react@18...">
</script>
<script cross origin
src="https://...react-dom@18/...">
</script>
<script>
const heading=react.create Element("h1",{},"Namaste Everyone");
const root=ReactDOM.createRoot(document.getElement By Id("root"));
root.vender(heading);
</script>
</body>
What is the { } denotes in above code ?
<div id="root">
<h1 id="title">Namaste Everyone </h1>
</div>
- id="title" - From the above code, This should come inside{ } whatever I’m passing inside{ } will goes as tag attributes of h1
React will overwrite everything inside “root” and replaces with whatever given inside render .
Do the below HTML code using React.
<div id="container>
<h1> Heading1 </h1>
<h2> Heading2 </h2>
</div>
To Build a Structure like this using React;⮷
<script cross origin src="https://react@18..."/> <script cross origin src="https://react-dom..."/> <script> const heading= React-create Element( "h1" { id: "title", } "Heading 1" ); const heading2= React.create Element( "h2",{id:"title2",},"Heading2"); const container= React.create Element( "div", {id:"container"}, [heading,heading2]); const root= ReactDOM.create Root( document.get Element By Id("root"); root.render(container);
"But, JSX makes life more easy".
Why React is known as 'react' ?
- Because it was designed to help developers “react” to changes In the state of an application, by efficiently rendering and updating the UI in response to those changes.
Igniting our App
We will build our own 'create_React_app'.
Code A:-
const heading= React.create Element(
"h1",
{
id:"title",
}
"Heading1"
);
➤This code is exactly similar to:-
Code B:-
<h1 id="title"> Heading1 </h1>
- ie, Code A will produce Code B in our DOM
- If I want to create div having 2 children h1 and h2, I’ll do it like this:-
const container= React.create Element( "div", //create Element takes first argument as the 'tag' { id:"container", //second argument is the attributes } [heading1,heading2] //third argument is the children );
The above code will be like this ⮷ inside DOM
<div id="container">
<h1 id="title"> Heading1 </h1>
<h2 id="title"> Heading2 </h2>
#Inside Second argument, we can write anything-Below given is call Props,props can be anything
{
id="container"
hello="world"
}
To make an app production ready,
we should:-
- Minify our life. (Remove our Console logs bundle things up)
- Need a server to Run things.
Even though we can load our “App.js”, We can't get optimised Version.
"Minify ➪ Optimization ➪ Clean console ➪ And Bundle"
In React, to get external functionalities , we use "BUNDLERS":-
- Webpack is a bundler
- Vite
- Parcel
In create_React_app, the bundler used is "webpack".
Most bundlers do the same job.
- Bundlers are packages. If we want to use a package in our code, we have to use a “Package manager”.
- We use a package manager known as NPM or YARN
NPM:- No Problem Man
- 'npm' does'nt mean node package manager but everything else.
- npm init (create a package json file)
- We use npm because we want a lot of packages in our project / react app.
- [npm init-y] <-This will skip lot of options.
npm install -D parcel
- From the above code, D= Dev dependency - (Because we want It in our Developer machine)
- Parcel = parcel is one of the dependency.
- Then, we’ll get package-lock.json
- [Caret & tidle sign -> Read.]
- Our project will automatically Update if We can use carot Sign (^)
Package-lock.json
- Will tell you which exact version of the library you are using.
Common issue
Something is working On my local host / My machine But not works in production, why ?
- Package-lock file Tells the exact version of the library we are using.
- Supper for Dev Dependency We’ve using 2.8.4 Version & Is might In package-lock json file.
- But in “package.json” file,It Will be like “2.8.2”
- Package-lock file is an Important file That locks the version.
"Node_modules"
- Which get installed is like a database For the npm.
- This is where the superpowers comes from.
- Our app has dependency on “parcel”.
- Parcel also has dependency on Something else.
All these dependencies / superpowers are in “node_modules”.
We don't put 'node_modules' into git, Why ?
- Because, our package-lock.json file have sufficient information to recreate node_modules
- Package-lock.json file keep and maintain the version Of everything in the Node_modules
- 'node_modules' in our machine can be regenerated in server using the package-locj.json file.
Previously, We used CDN links to get react into our app. This is not a good way ... We need to keep react in our node-modules.
To ignite our app.
- It means execute using npm & it is the entry point.
- Click 'Enter'
- Then, a mini server is created for us like localhost:1234
- Parcel given a server to us.
- "Parcel" ignited our app.
- As we removed CDN links, we don't have react in our app.
- So, we want to import it into our app.
- For that we use the keyboard "import"
Never touch 'node_modules' & 'package-lock.json'
As we got an error, we have to specify to the browser that 'we are not using a normal script tag, but a module'.
<script type="module" src="App.js"> </script>
We cannot import & export scripts inside a tag.
Modules can import and export.
Note:
◉ Hot Module Reload (HMR)
- Means that parcel will keep a track of all the files which you are updating
◉ How HMR works ?
- There is file watcher algorithms ( written in C++ ).
- It keeps track of all the files which are changing real time and it tells the server to reload.
- These are all done by parcel.
- There will be a folder called parcel-cache which will be there automatically.
- In our project, parcel need some space. so, it creates parcel cache.
- 'Dist’ Folder keeps the files minified for us.
- When we run command- npx parcel index.html
- This will creates a faster development version of our project and serves it on the server.
- When I tell parcel to make a production build: npx parcel build index.html
- It creates a lot of things, minify your file.
- And “ parcel will build all the production files to the dist folder ”
What takes a lot of time to load In a website ?
[Media - Images]
- Parcel does image optimization also.
- Parcel also does "Caching while Developement".
- Parcel also takes care of your older version of browser.
Compactible with older version of browser
Sometimes we need to test our app on https because something only works on https. parcel gives us a functionality that we can just Build our app on https on dev machine.
npx parcel index.html --https
- We should put the parcel-cache in git ignore.
- Because, anything which can be auto-generated should be put inside git ignore.
- Parcel uses: [Consistent Hashing Algorithms]
- Parcel is 'zero config'.
'Parcel' features in a glance:
- HMR- Hot Module Reloading.
- File Watcher algorithm - c++
- Bundling
- Minify code
- Cleaning our code
- Dev and Production build
- Super fast build algorithm
- Image optimization
- Caching while Developement
- Compression
- Compactible with older browser version
- HTTPS on Dev
- Port number
- Consistent Hashing Algorithm
- Zero config
- Tree Shaking
Transitive Dependencies
We have our package manager which handles and takes care of our transitive dependencies of our code. If you have to build a production trading app, which uses all optimizations ( like Minify, clean bundling , compression, consistent hashing etc…). We need to do all these. But we can't do this alone. We need some dependencies are also depended on many other dependencies.
How do I make our app compactible with older browser ?
- There is a package called 'browser list' and parcel automatically gives it to us.
- Browsers list makes our code compactible for a lot of browsers.
- go to "browser list.dev"
- In package json file, do:- "browser list": [
"last 2 versions"
] - It means my parcel will make sure that my app works in last 2 versions of all the browsers available.
- If you don't care about Other Browser , except Chrome . Then use,
- "browserslist": ["last 2 chrome versions"]
Finally,
"Parcel is a Beast"...
◉ Tree Shaking
- parcel has this superpower.
- means removing unwanted code.
Eg: Suppose your app is importing a library which has a lot of functions ( say 20 helped funths ).Then, all those 20 fns Will come into your code. But in my app, I may want to use only 1 or 2 out of it. Here, parcel will ignore all the unused code.
Create-react-app: uses 'Webpack' along with 'babel'.
How can you build a performant-web-scalable app ?
- There are so many things that react optimises for us and parcel (bundlers) gives us.
- Our whole application is a combination of all these things.
Pollyfill
- To make older browser understand our new code, the new code is converted into a older code which browser can understand, is called pollyfill.
- Babel do this conversion automatically.
Eg:- ES6 Is the newer version of JavaScript.
If I am working on 1999 browser, my browser will not understand what is this
Const, newprime , etc... - So, there is a replacement code for these functionalities which is compactible with older version of Browsers.
- So, this is what happen when we write “ browser list” -> our code is converted to older one.
Eg:- ES6 Is the newer version of JavaScript.
If I am working on 1999 browser, my browser will not understand what is this
Const, newprime , etc...
Babel
- It is a JavaScript package / library used to convert code written in newer versions of JS (ECMA Script 2015,2016,2017 etc..)Into code that can be run in older JS engines.
- To run our app, command is:-
[ npx parcel index.html ] - We always don't have to write this command.
- Generally, we build a script inside package.json. Which runs this command in an easy way.
Package.json
"Scripts": {
"Start":"parcel index.html"
"test":"jest"
}
So, to run the project i've to use:-
[ npm run start ]
"Start" Script execute this command.
Build Command
[ npx parcel build index.html ]
"Scripts":{
"build":"parcel build index.html"
}
Note:-
npx=npm run
So, npm run will build a project.
Console logs are not removed automatically by parcel. You have to configure your projects to remove it.
- There is a package which helps to remove console logs:-
babel-plugin-transform-remove-console - Before installing this package, create a folder called babelrc - For configuration.
- And Include:-
babel-plugin-transform-remove-console
{ "plugins":[["transform-remove-console", {"exclude":["error","warn"]}]] }
- Then, build: npm run build to see that all console logs are removed.
Render- means updateing something in the DOM.
Reconciliation
- Hepls to make React applications fast and efficient by minimizing the amount of work that needs to be done to update the changes.
- So, you don't have to worry about what changes on every update.
Eg:-
<ul>
<li>first</li>
<li>second</li>
</ul>
When adding an element at the end of the children: The tree works well.
<ul> <li>first</li> <li>second</li> <li>third</li> </ul>
Render() function as creating a tree of react elements
On the next state or props update, render() fn will return a different tree of React elements.
Whenever react is updating the DOM, for eg:-
<ul>
<li>Duke</li>
<li>Villanova</li>
</ul>
Now, I introduced one child over the top then react will have to do lot of efforts,
react will have to re-render everything. That means; [react will have to change the whole DOM tree.]
<ul>
<li>connecticut</li>
<li>Duke</li>
<li>Villanova</li>
</ul>
As react has to re-render everything, it will not give you good performance.
In large-scale application, it is far too expensive.
Solution - Introduction of keys
- React supports 'key' attribute.
- When children have keys, react uses the key to match # children in subsequent tree. Thus, making tree-conversion efficient.
<ul>
<li key='2014'>Connecticut</li>
<li key='2015'>Duke</li>
<li key='2016'>Villanova</li>
</ul>
Thus, react has to do very less work.
So, always use keys whenever you have multiple childrenchildren.
Create Element:
- React create Element() is creating an object.
- This object is converted into HTML code and put sheet upon DOM.
- If you want to build a big HTML structure, then using “create Element()” is not a good solution.
- So, there comes introduction of JSX.
JSX
When Facebook created react, the major concept behind bringing react was that we want to write a lot of html using JavaScript because JS is very performant.
import {create Element as ce}from "react"
const heading=.ce(
"h1",
{
id:"title"
Key:"h1"
}
"Hello World"
);
Instead of writting all these⇧,We can write them using JSX⇩:-
const heading=
<h1>Hello World</h1>
- JSX is not 'HTML inside javascript'
- JSX has 'HTML-like' syntax
This is a valid javascript code:-
const heading=(
<h1 id="title" key="h1"
Hello world
</h1>
);
React keeps track of 'Key'.
What is diff between HTML & JSX ?
- Our browser cannot understand JSX.
- 'Babel' understands this code.
What are different usage of JSX ?
- JSX uses react create element behind the scenes.
How to create image tags inside JSX ?
JSX ➪ React create element ➪ Object ➪ HTML(DOM)
Babel converts JSX to react create element()
(Read Bable’s documentation)
JSX Is created to empower react.
Advantages of JSX
- Developer experience
- Syntactical sugar
- Readability
- Lesscode
- Maintainability
- No Repeatition
Babel comes along with parcel.
JSX Is created to empower react.
Advantages of JSX
- Developer experience
- Syntactical sugar
- Readability
- Lesscode
- Maintainability
- No Repeatition
COMPONENT
"Everything is a Component in React"
React Components:-
- There are 2 types
- Functional component- New way.
- Class based component- old way
Functional component:-
- It is nothing but A JavaScript function
- It is a normal JS function which returns some piece of react elements (JSX)
Eg:-
const HeaderComponent=()={ return <h1>Hello World</h1> };
For any component, Name starts with capital letter.(It is not mandatory, but it is a convention)
To render functional component, write:-
<Header Component/>
React element:
const Heading=(
<h1 id="title"
Key="h1">
Hello World
</h1>
);
React element is finally an object.
Functional component:
const Heading=()=>{
return(
<h1 id="title"
Key="h1">
Hello World
</h1>);
};
Functional component is finally a function.
The Next Amazing thing:-
const Title=()=> {
<h1>Hello World</h1>
}
The above given is a functional component.
const Header Component=()=> {
return(
<div>
<Title/>
<h2>Namaste React</h2>
<h2>Hai all</h2>
</div>
);
};
This is a normal javascript function.
NB:
- Whenever you write JSX, you can write any piece of JavaScript code between parentheses { }.It will work.
- JSX is very secure.
- JSX makes sure your app is safe.
- It does sanitization.
const data=api.get Data();
const Header Component=()=>{
return(
<div>
{data}
<h2>Hello World</h2>
</div>
);
};
Component Composition
If i have to use a component inside a component. Then, it is called component composition / composing components.
"Building a Food-ordering app"
- Is JSX mandatory ? => No
- Is Typescripte mandatory ? => No
- Is ES6 mandatory ? => No
3 ways of component composition:-
- { Title() }
- <Title/> --> used generally
- <Title></Title>
BUILDING OUR APP
Name : Food Villa
"Whenever you are writing code, do planning"
our app look like this ⤵
So, the app layout should have:-
- Header
- Body
- Footer
const AppLayout =()=> {
return(
-Header
-Logo
-Nav Items (on right side)
-cart
-Body
-Searchbar
-Restaurant List
-Restaurant Card
-Image
-Name
-Rating
-Cusines
-Footer
-links
-copyrights
) }
HEADER COMPONENT
App.js
For building header component :-
const Title =()=> {
<a href="/">
<img
alt="food_villa_logo"
src="https://some url"
/> </a>
};
const Header Component =()=> {
return(
<div className="header">
<Title/>
<div className="nav-items">
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
<li>Cart</li>
</ul>
</div>
</div>
);
};
Note:-
JSX expression must have one parent element.
React.Fragment
- It is a component which is exported by 'React'.
[import React from "react";] - Group a list of children without adding extra nodes to the DOM.
- Eg:- import React from 'react'.
[import React from "react";]
const AppLayout=()=> {
return(
<React.Fragment>
<Header/>
<Body/>
<Footer/>
</React.Fragment>
);
};
- Short-hand syntax <> </> is used instead of <React.Fragment> </React.Fragment>
- But, you can't pass styles to empty brackets.
Giving Style inside React:
To give inline styles in react, do:-
➤ First Method ⮷
const style Obj = {
background colour:"red",
}
const jsx=(
<div style={style obj}> -->#inside this you can write any JS code
<h1>Hello</h1>
<h2>World</h2>
</div>
);
- In react, style is given using javascript objects.
- Alternative way ⮷
const jsx =( <div style={{ background colour:"yellow"; }}> <h1>Hello</h1> <h2>World</h2> </div> );
➤ Second Method ⮷
- Give class name to the div (or whatever tag) and write CSS inside CSS file.
const jsx =( <div classname="jsx"> <h1>Hello</h1> <h2>World</h2> </div> );
CSS file ⮷
jsx {background colour:"blue";}
➤ Third Method ⮷
- Using external library like "Tailwind CSS", "Bootstrap", "Material UI",etc..
Can i use a 'React.Fragment' inside my 'React.Fragment' ?
- Yes, you can nest 'React.Fragment' components inside other 'React.Fragment' components.
Eg:-
import React from 'react'; const jsx=( <> <child A/> <> <child B/> <child C/> </> <child D/> </> ); }
Body Component
While building restaurant cards, we need some data for this card .
Ways:-
- Using hard coded data.
- Integrate with api
Hard coded data-code will be like ⮷
const Restaurant card=()=> {
return(
<div classname="card">
<img src="https://some url">
<h2>Burger king</h2>
<h3>Burgers,American</h3>
<h4>4.2 stars</h4>
</div>
);
};
const Body=()=> {
return(
<div>
<Restaurant card/>
</div>
);
};
The name, image and all other datas shown in the above card won't be same always. So, it should be dynamic.
As we are using JSX , we can do javascript inside HTML.
Making data dynamic ⮷
const burger King={
name:"BurgerKing",
image:"https://some url",
cusines:["Burger","American"]
rating:"4.2"
}
In real world data does not comes like this ⤴
const RestaurantCard=()=>{
return(
<div classname="card">
<img src={burgerking.image}/>
Start write the next paragraph here