Download as pdf or txt
Download as pdf or txt
You are on page 1of 85

Unit 1

What is React JS?


● ReactJS is an open-source, component based front end library
responsible only for the view layer of the application. It is maintained by
Facebook.
● ReactJS uses virtual DOM based mechanism to fill in data (views) in
HTML DOM. The virtual DOM works fast owning to the fact that it only
changes individual DOM elements instead of reloading complete DOM
every time
● React is a declarative, efficient, and flexible JavaScript library for
building user interfaces. It lets you compose complex UIs from small and
isolated pieces of code called “components”.
Features of React
● Declarative: React makes it painless to create interactive UIs. Design simple views for
each state in your application, and React will efficiently update and render just the right
components when your data changes. Declarative views make your code more
predictable, simpler to understand, and easier to debug.
● Component-Based: Build encapsulated components that manage their own state, then
compose them to make complex UIs. Since component logic is written in JavaScript
instead of templates, you can easily pass rich data through your app and keep state out of
the DOM.
● Learn Once, Write Anywhere: We don't make assumptions about the rest of your
technology stack, so you can develop new features in React without rewriting existing
code. React can also render on the server using Node and power mobile apps
using React Native.
History of React
● React was created by Jordan Walke, a software engineer at Facebook, who released an early
prototype of React called "FaxJS”.He was influenced by XHP, an HTML component library for PHP.
It was first deployed on Facebook's News Feed in 2011 and later on Instagram in 2012. It was open-
sourced at JSConf US in May 2013.
● React Native, which enables native Android, iOS, and UWP development with React, was
announced at Facebook's React Conf in February 2015 and open-sourced in March 2015.
● On September 26, 2017, React 16.0 was released to the public.
● On February 16, 2019, React 16.8 was released to the public. The release introduced React Hooks.
● On August 10, 2020, the React team announced the first release candidate for React v17.0, notable
as the first major release without major changes to the React developer-facing API.
History of React
React was released by Facebook’s web development team in 2013 as a view
library, which makes it the ‘V’ in the MVC (model view controller).
As a view, it allows you to render components as viewable elements in a browser,
while its ecosystem lets us build single page applications.
While the first generation of frameworks tried to solve many things at once, React is
only used to build your view layer; specifically, it is a library wherein the view is a
hierarchy of composable components.
What is JSX?
React allows us to write components using a domain-specific language called JSX.
JSX allows us to write our components using HTML, whilst mixing in JavaScript
events. React will internally convert this into a virtual DOM, and will ultimately
output our HTML for us.

JSX is an extension created by Facebook that adds XML syntax to JavaScript.


What is JSX?
What is JSX?
import React from 'react'
const Hello = () =>{
// using jsx
// return(
// <div // without jsx
return React.createElement(
className='dummyclass'> 'div',
// <h1> // null,
// Hello react! {id:'hello',className:'dummyClass'},
React.createElement('h1',null,'hello react')
// </h1> )
// </div> }
export default Hello
// )
Installation or Setup
Installation or Setup
https://nodejs.org/en/download/
npx create-react-app hello-world
Cd hello-world
Npm start

http://localhost:3000
npx is an NPM package runner which gets installed when
you install node

NOTE: You’ll need to have Node >= 14.0.0 and npm >= 5.6 on your machine. To create a project, run:
Installation or Setup
install the package globally using the command prompt
npm install -g create-react-app
once it is installed you can run the command create react app followed by the project name
Then run the generator in your chosen directory.
Npx create-react-app my-app
Navigate to the newly created directory and run the start script.
cd my-app/
npm start
Basic folder structure
Basic folder structure
package.JSON: contains the dependencies

manifest.JSON is concerned with progressive web apps

the index.HTML is the only HTML file you are going to have in your application
Workflow

src/Index.js src/App.js public/index.html


ReactDOM.render( <p>
Hello React. <body>
<React.StrictMode>
save and open web page auto <noscript>You need to enable
<App />
change JavaScript to run this
</React.StrictMode>, </p>
<a app.</noscript>
className="App-link" <div id="root"></div>
document.getElementById('root')
href="https://reactjs.org" <div id="portal-root"></div>
); target="_blank"
</body>
rel="noopener noreferrer"
>
Learn React
</a>
</header> */}
</div>
);
}

export default App;


App.js
<img src={logo} className="App-logo" alt="logo" />

import React, { Component } from <p>


'react';
Edit <code>src/App.js</code> and save to reload.
import logo from './logo.svg';
</p>
import './App.css'; <a className="App-link" href="https://reactjs.org" target="_blank"
rel="noopener noreferrer" > Learn React </a>
// component declaration
</header>
class App extends Component {
</div>
render() {
);
return ( }

<div className="App"> }

<header className="App-header"> export default App;


Creating variable in app.js
import React, { Component } from 'react'; ● The render method returns a description of
import './App.css'; what you want to see on the screen. React
takes the description and displays the
class App extends Component {
result. In particular, render returns a React
render() {
element, which is a lightweight description
var helloWorld = 'Welcome to React'; of what to render.
return (
<div className="App">
<h2>{helloWorld}</h2>
</div>
);
}
}
export default App;
ES6
What is ES6?
ES6 stands for ECMAScript 6.
ECMAScript was created to standardize JavaScript, and ES6 is the 6th version of ECMAScript, it was
published in 2015, and is also known as ECMAScript 2015.

Why Should I Learn ES6?

React uses ES6, and you should be familiar with some of the new features like:
•Classes
•Arrow Functions
•Variables (let, const, var)
•Array Methods like .map()
•Destructuring
•Modules
•Ternary Operator
•Spread Attributes/operator
Spread Attributes/operator
● It's called spread attributes and its aim is to make function sum(x, y, z) { return x + y + z;}
the passing of props easier. const numbers = [1, 2, 3];
● Let us imagine that you have a component that console.log(sum(...numbers));
accepts N number of properties. Passing these // expected output:6
down can be tedious and unwieldy if the number
console.log(sum.apply(null, numbers));
grows.
// expected output: 6
● <Component x={} y={} z={} /> Thus instead you do
this, wrap them up in an object and use the
spread notation
● var props = { x: 1, y: 1, z:1 }; <Component
{...props} /> which will unpack it into the props
on your component, i.e., you "never" use {...
props} inside your render() function, only when
you pass the props down to another component.
Use your unpacked props as normal this.props.x.
Destructuring
<!DOCTYPE html>
<html>
● We may have an array or object that we are
working with, but we only need some of the
<body> items contained in these.
<script> ● Destructuring makes it easy to extract only
function calculate(a, b) { what is needed.
const add = a + b;
const subtract = a - b;
const multiply = a * b;
const divide = a / b;

return [add, subtract, multiply, divide];


}

const [add, subtract, multiply, divide] = calculate(4, 7);

document.write("<p>Sum: " + add + "</p>");


document.write("<p>Difference " + subtract + "</p>");
document.write("<p>Product: " + multiply + "</p>");
document.write("<p>Quotient " + divide + "</p>");
</script>

</body>
</html>
Destructuring
//without destructuring //using destructuring
<!DOCTYPE html>
const vehicleOne = { <html>
brand: 'Ford',
<body>
model: 'Mustang',
type: 'car', <p id="demo"></p>

year: 2021, <script>


const vehicleOne = {
color: 'red' brand: 'Ford',
} model: 'Mustang',
type: 'car',
year: 2021,
myVehicle(vehicleOne); color: 'red'
}

// old way myVehicle(vehicleOne);


function myVehicle(vehicle) { function myVehicle({type, color, brand, model}) {
const message = 'My ' + vehicle.type + ' is a const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';
' + vehicle.color + ' ' + vehicle.brand + ' ' + document.getElementById("demo").innerHTML = message;
vehicle.model + '.'; }
</script>
}
</body>
</html>
ES6 const and let
// not allowed
const helloWorld = 'Welcome to the Road to learn React';
helloWorld = 'Bye Bye React';

// allowed
let helloWorld = 'Welcome to the Road to learn React';
helloWorld = 'Bye Bye React';

However,
// allowed
const helloWorld = {
text: 'Welcome to the Road to learn React'
};
helloWorld.text = 'Bye Bye React';
return (
<div className="App">
<h2>{helloWorld.text}</h2>
</div>
);
Var vs let vs const
var a //declaration
a = 5 // initialization
let b //declaration
b = 10 //initialization
var c = 5 //declaration plus initialization in one step
let d = 5 //declaration plus initialization in one step
const a ; // SyntaxError: Missing initializer in const declaration
a = 5;
console.log(a);
const a = 5
console.log(a) //5

1: when we start our variable with var, let is called declaration. e.g: var a; or let a;
2: when we start our variable and assigning value it is declaration and initialization with value
3: const cannot be declared only, you need to initialize it with declaration
Var vs let vs const
import React, { Component } from 'react';
//capital first letter
// fun1(true);
class Let_var extends Component { return (
render() {
var helloWorld = 'Welcome to React'; <div
// const helloWorld = 'Welcome to the
Road to learn React';
className="App">
// helloWorld = 'Bye Bye React';
// let helloWorld = 'Welcome to the
Road to learn React';
<h2>{helloWorld}</h2>
// helloWorld = 'Bye Bye React'; </div>
// function fun1(a)
// { );
//
//
let helloWorld="ok global";
var hello = 'Welcome';
}
// if(a) }
// {
// let helloWorld = 'Welcome
to the Road to learn React';
//
to React';
var helloWorld1 = 'Welcome
export default Let_var;
// }
// console.log(helloWorld);
// console.log(hello);
// }
Var vs let vs const
1: var and let can change their value and const cannot change its
value
2: var can be accessible anywhere in function but let and const can
only be accessible inside the block where they are declared.
ReactDOM(index.js)
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
<React.StrictMode>
<App />
//it can also pass simple JSX.
{/* <h1>hello</h1> */}
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
ReactDOM.render(
<React.StrictMode>

ReactDOM
<App />
//it can also pass simple JSX.
{/* <h1>hello</h1> */}
</React.StrictMode>,
document.getElementById('root')
);

ReactDOM.render() uses a DOM node in your HTML to replace it with JSX.


ReactDOM.render() expects two arguments. The first argument is for rendering the JSX.
<React.StrictMode>
<App />
//it can also pass simple JSX.
{/* <h1>hello</h1> */}
</React.StrictMode>

The second argument specifies the place where the React application hooks into your
HTML. It expects an element with an id='root', found in the public/index.html file.
document.getElementById('root')
);
Map function(in App.js) class App extends Component {
render() {
import React, { Component } from 'react'; return (
import './App.css';
const list = [ <div className="App">
{ {list.map(function(item) {
title: 'React', return <div>{item.title}</div>;
url: 'https://reactjs.org/', })}
author: 'Jordan Walke', </div>
num_comments: 3,
points: 4, );
objectID: 0, }
}, }
{ export default App;
title: 'Redux',
url: 'https://redux.js.org/',
author: 'Dan Abramov, Andrew Clark',
num_comments: 2,
points: 5,
objectID: 1,
},
];
Map function
const Array = [2, 3, 4, 5, 35]
map() creates a new array from
calling a function for every array const Array = Array.map(Item => {
element. return Item * 2

map() calls a function once for each })


element in an array.

map() does not execute the function


console.log(Array)
for empty elements.

map() does not change the original


array.
With id
{list.map(function(item) { // don't do this
return (
{list.map(function(item, key) {
<div key={item.objectID}>
<span> return (
<a href={item.url}>{item.title}</a>
</span> <div key={key}>
<span>{item.author}</span>
...
<span>{item.num_comments}</span>
<span>{item.points}</span> </div>
</div>
); );
})} })}
ES6 Arrow Functions
// function declaration // allowed
function () { ... }
item => { ... }
// arrow function declaration
() => { ... } // allowed

You can remove the parentheses in an arrow (item) => { ... }


function expression if it only has one argument
// not allowed

item, key => { ... }

// allowed

(item, key) => { ... }


Map function vs Map using Arrow Functions
{list.map(function(item) { {list.map(item => {
return ( return (
<div key={item.objectID}> <div key={item.objectID}>
<span> <span>
<a href={item.url}>{item.title}</a> <a href={item.url}>{item.title}</a>
</span> </span>
<span>{item.author}</span> <span>{item.author}</span>
<span>{item.num_comments}</span> <span>{item.num_comments}</span>
<span>{item.points}</span> <span>{item.points}</span>
</div> </div>
); );
})} })}
Es6 Classes
<!DOCTYPE html>
<html>

<body>

<script>
class Car {
constructor(name) {
this.brand = name;
}
}

const mycar = new Car("Ford");

document.write(mycar.brand);
</script>

</body>
</html>
Es6 Promise
Promises used in JavaScript for asynchronous programming. For asynchronous programming, JavaScript used
callbacks but there is a problem using the callback which is callback hell or Pyramid of Doom. Using the ES6
Promise will simply avoid all the problems associated with the callback.
Es6 Promise
A Promise is always in one of the following states:
f1(function(x){
● fulfilled: Action related to the promise succeeded.
● rejected: Action related to the promise failed.
f2(x, function(y){ ● pending: Promise is still pending i.e not fulfilled or
rejected yet.
f3(y, function(z){ ● settled: Promise has fulfilled or rejected

...
.then(): Invoked when a promise is kept or broken. It can be
}); chained to handle the fulfillment or rejection of a promise

});
.catch() can be used for handling the errors(if any). It takes only one
function as a parameter which is used to handle the errors (if any)
});
Es6 Promise

● p is the promise object


● resolve is the function that should be called when the promise
executes successfully
● reject is the function that should be called when the promise
encounters an error.
Es6 Promise let p = new
Promise(function(resolve,reject){

let workDone = true; // some time


● p is the promise object consuming work

● resolve is the function that if(workDone){

should be called when the //invoke resolve function passed

promise executes resolve('success promise


completed')
successfully
}
● reject is the function that
else{
should be called when the
reject('ERROR , work could not be
promise encounters an error. completed')

})
Callback
//synchronous callback //asychronous callback uses timer
function show(){ function display(){
console.log("show"); setTimeout(function show(){
} console.log("show function
function display(callback){ calling");
callback(); }, 5000);
} console.log("display function
display(show); calling");
}
display();
//callback hell issue
addition(5,function(addres,err){

Callback
if(!err){
subtraction(addres,function(subres,err){
if(!err){
multiplication(subres,function(mulres,er
//asychronous anonymous callback r){
function display(callback){ if(!err){
console.log(mulres);
console.log("display function
}
calling"); });
callback(); }
});
}
}
display(function(){ });
console.log("show function
function addition (val,callback){
calling");
return callback(val+5,false);
}); }
function subtraction (val,callback){
return callback(val-3,false);
}
function multiplication (val,callback){
return callback(val*5,false);
}
Es6 Promise
var promise=new Promise(function(resolve,reject){
resolve(5);
// reject(5);
})
promise.then(addition).
then(subtraction).
then(multiplication).
then(function(ans){
console.log(ans);
}).catch(function(err){
console.log(err);
});

function addition (val){


return val+5;
}
function subtraction (val){
return val-3;
}
function multiplication (val){
return val*5;
}
Es6 Promise
var promise=new Promise(function(resolve,reject){ //callback hell issue
resolve(5); addition(5,function(addres,err){
// reject(5); if(!err){
}) subtraction(addres,function(subres,err){
if(!err){
promise.then(addition).
multiplication(subres,function(mulres,err){
then(subtraction).
if(!err){
then(multiplication). console.log(mulres);
then(function(ans){ }
console.log(ans); });
}).catch(function(err){ }
console.log(err); });
}); }
});
function addition (val){
return val+5; function addition (val,callback){
} return callback(val+5,false);
function subtraction (val){ }
function subtraction (val,callback){
return val-3;
return callback(val-3,false);
}
}
function multiplication (val){ function multiplication (val,callback){
return val*5; return callback(val*5,false);
} }
Es6 Promise
function add_positivenos_async(n1, n2) {
add_positivenos_async(-10, -20)
let p = new Promise(function (resolve, reject) {
.then(successHandler) // if promise resolved
if (n1 >= 0 && n2 >= 0) {
.catch(errorHandler);// if promise rejected
resolve(n1 + n2)

}
function errorHandler(err) {
else

reject('NOT_Postive_Number_Passed')
console.log('Handling error', err)

}) }

return p; function successHandler(result) {

} console.log('Handling success', result)

add_positivenos_async(10, 20) }

.then(successHandler) // if promise resolved console.log('end')

.catch(errorHandler);// if promise rejected


ES6 Modules
● In JavaScript ES6, you can import and export
functionalities from modules. These can be
functions, classes, components, constants,
essentially anything you can assign to a
variable.

● Modules can be single files or whole folders


with one index file as entry point

● module structure, a component is defined by


its component declaration in the JavaScript
file, but also by its style and tests
ES6 Modules

● A module organizes a related set of JavaScript code.


● A module can contain variables and functions.
● A module is nothing more than a chunk of JavaScript code written in a file.
● By default, variables and functions of a module are not available for use.
● Variables and functions within a module should be exported/imported so that they can be
accessed from within other files.
● Modules in ES6 work only in strict mode. This means variables or functions declared in a
module will not be accessible globally.
ES6 Modules
By default, variables and functions of a module are not available for use. Variables and functions within a module should be
exported so that they can be accessed from within other files. Modules in ES6 work only in strict mode.

The export keyword can be used to export components in a module. Exports in a module can be classified as follows −
● Named Exports
● Default Exports

● Named Exports: import the component with the exact same name
Named exports are distinguished by their names.
/using multiple export keyword

export component1

export component2

export componentN

Or

///using single export keyword

export {component1,component2,....,componentN}
ES6 Modules

● Default Exports
Modules that need to export only a single value can use default exports. There can be only one default export
per module.
import the component with any name

Syntax
export default component_name
ES6 Modules file2.js
import { firstname, lastname } from './file1.js';
file1.js console.log(firstname);
// output: Jordan
const firstname = ‘Jordan';
OR
const lastname = ‘Walke'; file2.js
import * as person from './file1.js';
export { firstname, lastname };
console.log(person.firstname);
// output: Jordan
OR
file2.js
import { firstname as username } from './file1.js';
console.log(username);
// output: Jordan
ES6 Modules
file1.js
There is also the default statement, which can be const r = {
used for a few cases: firstname: ‘Jordan ',
• to export and import a single functionality lastname: ‘Walke ',
};
• to highlight the main functionality of the export default r;
exported API of a module
file2.js
You have to leave out the curly braces to import
import developer from './file1.js';
the default export.
console.log(developer);
The import name can differ from the exported // output: { firstname: ‘Jordan ', lastname: ‘Walke ' }
default name
ES6 Modules
file1.js
file2.js
const firstname = 'Jordan'; import developer, { firstname, lastname }
const lastname = ‘Walke',; from './file1.js';
const person = {
console.log(developer);
firstname,

lastname, // output: { firstname: 'Jordan', lastname:


};
‘Walke' }
export { console.log(firstname, lastname);
firstname,
// output: Jordan Walke
lastname,

};

export default person;


React Components
React Components
A component represents a portion of the view of your application.

Note: "Props" are simply the attributes used on a JSX node (e.g. <SomeComponent
someProp="some prop's value" />),
Functional component
a functional component is a JavaScript App.js(This is not index.js)
function that accepts an input of properties import Greet from './components/Greet'
and returns HTML that describes the UI import MyComponent from './components/Greet'
...
Greet.js ...
function App() {
import React from 'react' return (
function Greet(){ <div className="App">
return <h1>hello react</h1> {/* using functional component */}
<Greet></Greet>
} {/* using different name in import */}
// export const Greet = () => <MyComponent></MyComponent>
</div>
//<h1> hello react!</h1> );
export default Greet }
export default App;
Functional Component
Use snippet “rsf’ to create default functional component
Class Component
import React, {Component} from 'react'
//class component
class Welcome extends Component{
render()
{
return <h1>hello react!</h1>
}
}
export default Welcome

Class components are simple classes


(made up of multiple functions that add
functionality to the application).
Class component: rcc snnipet
Class Component:Click Event
import React, { Component } from 'react';

class ClassClick extends Component {


clickHandler(){
console.log('click button in class component’);
alert("Button Clicked");
}
render() {
return (
<div>
<button onClick={this.clickHandler}>Click Me</button>
</div>
);
}
}
export default ClassClick;
Functional Components Class Components

A functional component is just a plain A class component requires you to extend from React.
JavaScript function that accepts props as an Component and create a render function which returns a
argument and returns a React element. React element.

There is no render method used in functional


It must have the render() method returning HTML
components.

Also known as Stateless components as


they simply accept data and display them in Also known as Stateful components because they
some form, that they are mainly responsible implement logic and state.
for rendering UI.

React lifecycle methods (for example,


React lifecycle methods can be used inside class
componentDidMount) cannot be used in
components (for example, componentDidMount).
functional components.

It requires different syntax inside a class component to


implement state management.
Hooks can be easily used in functional
example:
components.
constructor(props) {
example:
super(props);
const [name, SetName] = React.useState(‘ ‘)
this.state = {name: ‘ ‘}
}

Constructors are not used . Constructor are used as it needs to store state.
Handler function in JSX
Handler function in JSX
it has to be a function that is passed to the <button onClick={() => this.onDismiss(item.objectID)}
event handler. type="button">

When using onClick={doSomething()}, the Dismiss


doSomething() function executes immediately </button>
when the application is opened in a browser.
The expression in the handler is evaluated. ● using onClick={this.onDismiss} wouldn’t suffice,
because the item.objectID property needs to be
But using onClick={doSomething} where passed to the class method to identify the item that
doSomething is a function, it would only be should be dismissed.
executed if the button is clicked.
● We wrap it into another function to sneak in the
property. This concept is called higher-order
functions in JavaScript,
Handler function in JSX: Higher order
functions
<button onClick={() => this.onDismiss(item.objectID)} type="button">

Dismiss

</button>

using onClick={this.onDismiss} wouldn’t suffice, because the item.objectID property


needs to be passed to the class method to identify the item that should be dismissed.
We wrap it into another function to sneak in the property. This concept is called
higher-order functions in JavaScript,
Handler function in JSX
import React from 'react';
function FunctionClick(){
function clickHandler(){
console.log('button click in functional components')
}
return(
<div>
<button onClick={clickHandler}>
Click
</button>
</div>
)
//event handler "clickhandler" is a function dont use clickHandler() else it will become function call
}
export default FunctionClick
List component
function App() { ● JSX Lists Require a Key: Keys are unique identifiers that
const people = [ must be attached to the top-level element inside a map.
{ name: 'Jordan' }, ● Keys are used by React to know how to update a list whether
adding, updating, or deleting items.
{ name: 'Walke'} ● This is part of how React is so fast with large lists.
];
function App() {
return ( const people = [
<div> { id: 1, name: 'Jordan'},
{ id: 2, name: 'Walke’}
{people.map(person => (
];
<p>{person.name}</p> return (
))} <div>
</div> {people.map(person => (
); <p key={person.id}>{person.name}</p>
} ))}
</div>
export default App;
);
}
export default App;
Lists
import React from 'react'; <h2>
{names[0]}
function NameList(props) { </h2>
const names=['one','two','three']; <h2>
const {names[1]}
nameList=names.map(x=><h2>{x}</h2>); </h2>

return ( <h2>
<div> {names[2]}
</h2>
{ </div>
nameList }
);

// names.map(x=><h2>{x}</h2>)
} export default NameList;
Lists
import React from 'react'; <h2>
function NameList(props) { {names[0]}
</h2>
const names=['one','two','three'];
const nameList = names.map((x, index) => ( <h2>
{names[1]}
<h2 key={index}> </h2>
{index} <h2>
{x} {names[2]}
</h2> </h2>
</div>
)); );
// when list has no unique key, list is static you }

may use index export default NameList;


return (
<div>
{
nameList
// names.map(x=><h2>{x}</h2>)
}
Lists
import React from 'react'; return (
import Person from './Person'; <div>
{
personList
function NameList(props) { }
const persons=[
{ </div>
id:1, );
branch:'ce', }
subject:'web development'
}, export default NameList
{
id:2,
branch:'it',
subject:'python'
}
]
const personList=persons.map(x=><Person key={x.id}
x1={x}/>)
// key is used to update list item in match with key
value
// const personList=persons.map(x=>(<h2>{x.branch} in
{x.subject}</h2>))
Importance of key in list
Conditionals
● If else
● Ternary operator
● Element variables (changing state of variable)
● Short circuit operator
Conditionals
//index.js
//conditionals.js ……
const Spinner=()=><h1>Loading...</h1>; import MyComponent from
function MyComponent({isLoading}){ './components/conditionals';
ReactDOM.render(
if(isLoading)
<React.StrictMode>
return <Spinner/>; <MyComponent isLoading />
return <main>This is real //<MyComponent
Content</main> isLoading={false} />
} </React.StrictMode>,
document.getElementById('root')
export default MyComponent;
);
….
Conditionals
….
… const Spinner = () =>
const Spinner = () => <strong>Loading...</strong>;
<strong>Loading...</strong>; function MyComponent({ isLoading }) {
return (
function MyComponent({ isLoading }) { <main>
<h2>This is my app</h2>
if (isLoading) return <Spinner />;
{isLoading ? <Spinner /> : <article>This is
return <main>This is the real the real content</article>}
content</main>; </main>
);
}
}
… …
//Using a Normal if //Switching Elements Tree Using Ternaries
Conditionals
● Short circuit operator <script>
● In JavaScript short-circuiting, an expression is evaluated function gfg() {
// AND short circuit
from left to right until it is confirmed that the result of
document.write(false && true)
the remaining conditions is not going to affect the document.write("</br>");
already evaluated result. document.write(true && true)
● If the result is clear even before the complete evaluation document.write("</br>");
of the expression, it short circuits and the result will be // OR short circuit
returned. document.write(true || false)
document.write("</br>");
● Short circuit evaluation avoids unnecessary work and
document.write(false || true)
leads to efficient processing. }
gfg();
</script>
Conditionals
… ….
const Spinner = () => <strong>Loading...</strong>; const Spinner = () => <strong>Loading...</strong>;

function MyComponent({ isLoading }) { function MyComponent({ isLoading }) {


return ( return (
<main> <main>
<h2>This is my app</h2> <h2>This is my app</h2>
{isLoading ? <Spinner /> : null} {isLoading && <Spinner />}
<article>This is the real content</article> <article>This is the real content</article>
</main> </main>
); );
} }
… ….
//Rendering an Element or Null: Using a Ternary //Rendering an Element or Null: Using an Implicit Null
Single page applications
● A single-page application is an application that loads a single HTML page and all the necessary
assets (such as JavaScript and CSS) required for the application to run. Any interactions with the
page or subsequent pages do not require a round trip to the server which means the page is not
reloaded.

● Single page applications (SPA) have become increasingly popular in recent years, as frameworks
like Angular, Ember, and Backbone allow JavaScript developers to build modern web
applications using techniques beyond vanilla JavaScript and jQuery. The three mentioned are
among the first.

● SPAs, each coming into its own between 2010 and 2011, but there are many more options for
single- page development. The first generation of SPA frameworks arrived at the enterprise
level, so their frameworks are more rigid. React, on the other hand, remains an innovative library
that has been adopted by many technological leaders like Airbnb, Netflix, and Facebook.
Single page applications
Single page applications
Single page applications
Pros of a Single-page Application:

● Performance. All resources are loaded during one session, and then, when interacting with the page, only the
necessary data is changed. This approach significantly increases web app performance.
● Improved user experience. Such apps provide users with a more understandable linear experience. Moreover,
the use of AJAX and JavaScript frameworks, as well as the fact that there is only one web page, allows building a
more flexible and responsive interface.

● Data caching. After the first request to the server, all the necessary local data is stored in the cache, and that
provides users with the possibility to work in an offline mode (for example, GoogleDocs offline mode).

● Development speed. All things equal, you will have to develop and test fewer app elements and will be able to
reuse part of the code.

● Ease of debugging. An SPA is most often developed based on popular frameworks (React, Vue.js, AngularJS)
that offer their own debugging tools based on Google Chrome, for example, Vue.js devtools.
Multipage applications
Multipage applications
In the case of a multi-page app, the entire web page content is refreshed, which is
also true about all the pages requested by the user.
Multipage applications
Pros of a Multi-page Application:

SEO optimization is possible. The app has multiple pages, and each of them can be
optimized for a specific group of requests to get free organic traffic from Google.

Ease of scaling. This architecture type allows creating as many new pages for each
product or service as you like and implementing any changes in them.

Available ready-made solutions. As a rule, MPA development requires a smaller


technology stack, and besides, a wide range of ready-made solutions (CMS) are
available.

Analytic capabilities. Web analytics tools like Google Analytics can be easily
integrated into this type of project and allow tracking each business page’s performance.
Navigation Pages
import {Route,Routes} from 'react-router-dom'; import React from 'react’;
import Aboutus from './components/aboutus';
import { NavLink } from 'react-router-dom';
import Contactus from './components/contactus';
import User from './components/User';
import Menu from './components/Menu'; function Menu(props) {
function App() {
return (
return (
<div className="App"> <div>
<NavLink to='/' >Aboutus</NavLink>
<Menu></Menu> <NavLink to='/contact'>Contactus</NavLink>
<Routes>
<Route exact path="/"
<NavLink to='/user/abc'>User</NavLink>
element={<Aboutus/>}></Route> </div>
<Route path='/contact' );
element={<Contactus/>}></Route>
}
<Route path='/user/:name'
element={<User/>}></Route>
{/* //we can have error page for any random path */} export default Menu;
</Routes>
//install react-router-dom using npm
</div>
);
}
export default App;
Navigation Pages
import React from 'react'; import React from 'react';
import {useParams} from 'react-router-dom';
function Aboutus() { function User() {
return ( const {name}=useParams();
<div> return (
<h1>Aboutus</h1> <div>
</div> <h1>hello{name}</h1>
); </div>
} );
}
export default Aboutus;
export default User;

You might also like