React

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

UX Expert

With React Redux

By – Satya Priya Arya


UNIT 1
Refreshing ES6
Frontend v/s Backend v/s Database
The front end is the part of the website users can see
and interact with such as the graphical user interface
(GUI) and the command line including the design,
navigating menus, texts, images, videos, etc.
Examples – HTML, CSS, Java-Script, jQuery, React
The backend, on the contrary, is the part of the
website users cannot see and interact with.
Example – C, C++, Java, Node.JS, C#
The database used to store permanent information
Example – SQL Server, MySQL, MongoDB
What is React
React runs on various platforms (Windows, Linux,
Unix, Mac OS X, etc.)
React is a JavaScript library created by Facebook
React is a User Interface (UI) library
React is a tool for building UI components
History of React
Before 2009, web browsers used JavaScript.
JS was invented in the 1990 as a scripting language for
adding dynamic features to a web page from an HTML
file.
React is a JavaScript library created by Facebook in
2011
npm, a package manager for the Node.js environment,
was released in January 2010.
Current version is 18.2.0
Why React
Easy to learn
Reusable components
Fast rendering
SEO friendly
Strong community support
Virtual DOM
ES6
ES6 stands for ECMAScript 6
ES6 is also known as ECMAScript 2015
ECMA known as European Computer Manufacturers
Association - non-profit organization that develops
standards in computer hardware, communications,
and programming languages.
React uses ES6
In short ES6 is just some standards for JavaScript.
ES6 Continue…
First we will learn some basic java sript.
Then some new ES6 features
 Classes
 Arrow Functions
 Variables (let, const)
 Array Method (.map())
 Destructuring Arrays
 Modules
 Ternary Operator
 Spread Operator
 Multi line strings
 Default parameters
Sample HTML page with java script
 <html>
 <head>
 <script lang="javascript">
 function loadDoc(){
 document.getElementById("dynamic").innerHTML = "This is dynamic text " + Date();
 }
 </script>
 </head>
 <body>
 <div id="demo">
 <h2>Let Java Script change this text</h2>
 <button type="button" onclick="loadDoc()">Change Content</button>
 </div>
 <div id="dynamic"></div>
 </body>
 </html>
Basics of java script
 Explain basic tags
 HTML
 Title
 Head
 Script
 Function
 Document
 Body
 Id
 H2
 Button
 Console
 Comments
 Operator (+ - * /)
Data types
 Supports 8 data types.
 String
 Number
 Bigint
 Boolean
 Undefined
 Null
 Symbol
 Object
 Supports 3 object data types.
 Object – {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}
 Array - [“one”, “two”]
 Date - new Date("2022-03-25")
 All data types are dynamic
Functions
A JavaScript function is a block of code designed to
perform a particular task
Functions often compute a return value. The return
value is "returned" back to the "caller"
var x = Add(40, 13);
function Add(a, b) {
return a + b;
}
Write a program to convert Fahrenheit to Celsius
More statements
IF
Else
Switch
Loop
Write a program to print day name from given 1 to 7
ES6 Classes
 One of the biggest addition of ES6 is classes
 Similar to used in any other languages
<html>
<body>
<script>
class Car {
constructor(name) {
this.brand = name;
}
price(){
return 100000;
}
}
const mycar = new Car("Ford");
document.write(mycar.brand);
document.write('<br/>');
document.write(mycar.price());
</script>
</body>
</html>
 Modify above script to print different price according to brand name.
ES6 Classes Inheritance
Use extends keyword to inherit a class.
Use super keyword to call parent constructor
Add following class in previous example and try with
added class
Class Model extends Car {
constructor(name, mod){
super(name);
this.model = mod;
}
show (){
return this.price() + “, is has ” + this.model
}
}
ES6 Arrow Function
It provides a more concise syntax for writing function
expressions by removing the "function" and "return"
keywords.
// ES5
var multiply = function(x, y) {
return x * y;
}
// ES6
const multiply = (x, y) => x * y;
Different styles
 Without parameter - multiply = () =>
 Single parameter - multiply = x =>
 More than one parameter = multiply = (x,y) =>
ES6 Variables
Before ES6 we have only var keyword declaration
ES6 added let and const style of variable declaration
Problem with var is that is has function scope, not a
block scope.
But let has block scope
Const also has block scope. In addition it’s value can
never change.
ES6 Array method .map()
Very useful function of ES6
.map() method allows you to run a function on each
item in the array, returning a new array as the result.
const myArray = ['apple', 'banana', 'orange'];
const myList = myArray.map((item) => <p>{item}</p>)
With index example
list.map((currElement, index) => {});
ES6 Destructuring Arrays
It makes very easy to working with arrays
Old way
 Var fruits = ["Apple", "Banana"];
 Var a = fruits[0]
 Var b = fruits[1]
Array Destructuring
 let fruits = ["Apple", "Banana"];
 let [a, b] = fruits;
 console.log(a, b);
Object Destructuring
 let person = {name: "Peter", age: 28};
 let {name, age} = person;
 console.log(name, age);
ES6 Modules
We can keep our JS code into a separate file
Allow us to create modules (modular programming)
Export and import keyword used for this purpose
Below example shows 2 exports saved in a file mymod.js
 export var num = 50;
 export function getData(data) {
 //long calcuation

 };

Use above modules in new file


 import { name, getData } from "./mymod.js";
ES6 Ternary Operator
Simplified version of if/else statement
Exactly same as C language
 Codition ? True : false
ES6 Spread Operator
 One more helpful operator
 Used to quickly copy all or part of an existing array or object into another array or
object
 In old version we use array1.concat(array2) to concatenate 2 arrays.
 Let’s try with new way of ES6
 const numbersOne = [1, 2, 3];
 const numbersTwo = [4, 5, 6];
 Check output of following statements.
 const numbersCombined = [...numbersOne, ...numbersTwo];

 const [one, two, ...rest] = numbersCombined;

 Difference between – Explain with push an element after creating array2 and then
print both array.
 Let array2 = array1
 Let array2 = […array1]
 Difference between – after defining let arr = ['a','b'];
 let arr2 = [arr,'c','d'];

 let arr2 = [...arr,'c','d'];


ES6 Multi line strings
We can can create multi-line strings by using back-
ticks(`)
let greeting = `Hello World,
 Greetings to all,
 Keep Learning and
 Practicing!`
ES6 Default parameters
Default parameters simplified in ES6
In ES5
Var output = Add(a, b) {
 a = a || 100

 b = b || 200

}

In ES6
Var output = Add(a = 100, b = 200) {
}
Iterators
 A process that is repeated more than one time by applying the same logic is called an
Iteration.
 The following values are iterable:
 Arrays
 Strings
 Maps
 Sets
 If the loop is executed 6 times continuously, then we could say the particular block
has iterated 6 times.
 An iterator is an object that can access one item at a time from a collection while
keeping track of its current position
 It just requires that you have a method called next() to move to the next item to be a
valid iterator
 The result of next() is always an object with two properties –
 Value: The value in the iteration sequence
 Done: true | false
Iterator example
 Old way
 let ranks = [1,2,3,4,5];
 for (let index = 0; index < ranks.length; index++) {
 console.log(ranks[index]);
 }
 New way
 let ranks = [1,2,3,4,5];
 for (let key in ranks) {
 console.log(key);
 }
 The Symbol.iterator is a special-purpose symbol made especially for accessing an object's internal
iterator
 let ranks = [1,2,3];
 let iterator = ranks[Symbol.iterator]();
 console.log(iterator.next());
 console.log(iterator.next());
 console.log(iterator.next());
 console.log(iterator.next());
 Validate the output of above function
Generators
Generators are a special type of function in JavaScript
that can pause and resume state.
A Generator function returns an iterator, which can be
used to stop the function in the middle, do something,
and then resume it whenever.
Generator functions are written using the function*
syntax
function *generator() { // ... }
yield is an operator with which a generator can pause
itself
Generator example
function* stringGenerator() {
 yield 'hi 1';
 yield 'hi 2';
 yield 'hi 3';
}
 const strings = stringGenerator();
 console.log(strings.next());
 console.log(strings.next());
 console.log(strings.next());
 console.log(strings.next());
Validate the output of above function
UNIT 2
Getting started React
Practical Application
 We have lots of applications created in React
 Few examples are:
 Facebook
 Netflix
 Yahoo Mail
 BBC
 Cloudflare
 Trello
 Skyscanner
 Codecademy
 Dropbox
 Flipboard
 Scribd
 Asana
Why need React
 React is Easier to Learn Compared to Angular
 React is an elementary and lightweight library that only deals with the view layer of a
web page.
 It has an easy learning curve
 If you have a functional understanding of HTML-CSS and a basic understanding of
programming concepts, you can quickly start working with React.
 There are extensive documentation available online that will help you with everything
related to ReactJS.
 React Has a Large Development Community
 React is an open-source library
 It has amassed a massive following of JavaScript developers who develop new solutions
and tools regularly.
 A lot of user-developed applications have been included in the official library.
 You can get access to a large community of experts to solve any problems.
 React has more than 201K stars on Github and around 10 million npm
downloads weekly.
Why need React
 React Offers Reusable Components
 Components in ReactJS are independent, reusable bits of code.
 You can use them as a primary JavaScript function or a class component
 Each React component that you have developed can be reused in other parts of the app
 Virtual DOM
 Document Object Model or DOM is an interface that represents HTML and XML code
into trees.
 A web browser creates a DOM-like model to render output, treating each object/element
of the HTML code as a node in the DOM tree.
 Whenever a change occurs in the HTML code, either by user interaction or value updates,
the DOM tree has to be rendered again, leading to a lot of time and power consumption.
 ReactJS use of Virtual DOMs.
 React simply creates a copy of the DOM, maintaining a cache memory of sorts. Every time a
change is made, it examines the Virtual DOM and pinpoints exactly which tree nodes and
components need to be updated.
 With just a small change in the DOM, the tree can be updated quickly and efficiently. This
saves developers a ton of time and makes the application remarkably fast and responsive.
Why need React
 JSX increases the performance and efficiency of ReactJS
 JSX or JavaScript XML is a syntax extension for JavaScript.
 Facebook developed it to extend the functionalities of HTML structures
into JavaScript.
 With JSX, there is no requirement for separate HTML and JS codes.
 JSX, along with the Virtual DOM, increases the performance and
efficiency of ReactJS apps.
 React Hooks
 Hooks is an independent feature introduced in ReactJS 16.8 that enables
JavaScript developers to write states and other features in function
components.
 You don’t need to deal with the complicated classes anymore. Using
Hooks, you can easily manage state logic between components and share
data with components without props and classes.
How React Works
 When the app first starts, there is nothing in the Virtual DOM and the real DOM.
 As a result, the set of instructions supplied to ReactDOM must include instructions for
creating everything from the start.
 However, when we interact with the user interface, such as by clicking a button, the
application state is modified.
 The state variable is changed programmatically to include specific new or altered entries.
 However, in the further steps, the importance of the Virtual DOM becomes more
prominent.
 When a Component’s state value changes, React calls the Component’s render() function
again.
 Similarly, as previously, invoking render() will produce a tree of Elements.
 This time, the tree will incorporate a new Element to symbolize the new objects.
 React now has an old tree that describes what it currently looks like and a new tree that
represents how the updated page should look.
 React must now compare these two trees and provide ReactDOM with instructions to sync
anything that has changed, which results in adding items to the UI.
 This is How React works.
Leveraging Virtual DOM
 DOM
 The DOM represents the UI of your application. Every time there is a change in the state of your application UI, the DOM
gets updated to represent that change. Now the catch is frequently manipulating the DOM affects performance, making it
slow.
 Why DOM manipulation slow
 The DOM is represented as a tree data structure. Because of that, the changes and updates to the DOM are fast. But after the
change, the updated element and it’s children have to be re-rendered to update the application UI. The re-rendering or re-
painting of the UI is what makes it slow.
 Virtual DOM
 The virtual DOM is only a virtual representation of the DOM. Every time the state of our application changes, the virtual
DOM gets updated instead of the real DOM.
 Why Virtual DOM faster
 When new elements are added to the UI, a virtual DOM, which is represented as a tree is created. Each element is a node on
this tree. If the state of any of these elements changes, a new virtual DOM tree is created. This tree is then compared with the
previous virtual DOM tree.
 Once this is done, the virtual DOM calculates the best possible method to make these changes to the real DOM. This ensures
that there are minimal operations on the real DOM. Hence, reducing the performance cost of updating the real DOM.
 In React every UI piece is a component, and each component has a state. When the state of a component changes, React
updates the virtual DOM tree. Once the virtual DOM has been updated, React then compares the current version of the
virtual DOM with the previous version of the virtual DOM. Once React knows which virtual DOM objects have
changed, then React updates only those objects, in the real DOM. This makes the performance far better when
compared to manipulating the real DOM directly. This makes React standout as a high performance JavaScript library.
Setting up React
Install Node.JS from (It provides JavaScript runtime)
https://nodejs.org/
Install Visual Studio Code from
https://code.visualstudio.com/download
npx create-react-app reactapp
cd reactapp
Npm start
UNIT 3
JSX
What is JSX
JSX stands for JavaScript XML.
It allows us to write HTML in a React application.
JSX allows us to write HTML elements in JavaScript.
If you are familiar with HTML, then its very easy to
learn JSX.
We can create React application without JSX also, but
JSX makes it very easy to write React code.
JSX is an extension of the JavaScript language based on
ES6, and is translated into regular JavaScript at
runtime.
Code without JSX
import React from 'react';
import ReactDOM from 'react-dom/client';
const myElement = React.createElement('h1', {}, 'I am
not using JSX!');
const root =
ReactDOM.createRoot(document.getElementById('ro
ot'));
root.render(myElement);
Code with JSX
import React from 'react';
import ReactDOM from 'react-dom/client';
const myElement = <h1>I am using JSX!</h1>;
const root =
ReactDOM.createRoot(document.getElementById('ro
ot'));
root.render(myElement);

You might also like