Unit-1 Introduction To React and ES6 DSP
Unit-1 Introduction To React and ES6 DSP
• ECMAScript is the standardization of Javascript which was released in 2015 and subsequently
renamed as ECMAScript 2015.
• It’s fair to say that with the use of ES6 features we write less and
do more, hence the term ‘write less, do more’ definitely suits ES6.
Output:- Output:-
10 10
9 "error"
"TypeError: Assignment to constant
variable.”
ES6 Arrow Functions
• Arrow function {()=>} is concise way of writing JavaScript functions in shorter
way. Arrow functions were introduced in the ES6 version. They make our code
more structured and readable.
• Arrow functions are anonymous functions i.e. functions without a name but
they are often assigned to any variable. They are also called Lambda Functions.
Syntax:
const function_name = () => {
//Code
}
ES6 Arrow functions
• Example 1:- • Example 2:-
const Greet = (name) => {
const Greet = () => { console.log( "Hi from Semester-6
console.log( "Hi from Semester-6" ); ”+name );
} }
Greet(); Greet(“Alice”);
Output:- Output:-
Hi from Semester-6 Hi from Semester-6 Alice
Syntax:
function name(parameter=value,...parameters) { }
Default Parameters
In the given example observe that , while calling
Example:- the multiply function for first time we have not
function multiply(a, b) { provided any value for second argument. So,
there will be error while executing that line
return a * b;
} And while calling the multiply function we have
let num1 = multiply(5); provided value for second argument. So, these
statements will execute without any error.
console.log(num1);
let num2 = multiply(5, 8);
console.log(num2);
Output:-
NaN
40
Default Parameters
In the given example observe that , while calling
Example:- the multiply function for first time we have not
function multiply(a, b=1) { provided any value for second argument. So,
now it will consider default value of parameter b
return a * b; that is 1.
}
let num1 = multiply(5); And while calling the multiply function we have
provided value for second argument. So, these
console.log(num1); statements will execute without any error.
let num2 = multiply(5, 8); The value of parameter b will be considered as 8
(We have passed at function calling)
console.log(num2);
Output:-
5
40
Template Literals
• Template literals are a new feature that was introduced in ECMAScript6, which offers
a simple method for performing string interpolation and multiline string creation.
• The template literals were called template strings before the introduction of ES6.
Starting from ES6 (ECMAScript 6), we have Template Literals which are indicated by
the backtick (` `) character. Template literals can also be used to hold the placeholders,
that are indicated by the ‘$’ sign and the {} braces such as (${expression}).
Syntax:
`Any string ${jsExpression} can appear here`
Template Literals
Example :-
const str1 = `Hi, Full Stack Developer`;
console.log(str1);
const sem =“Sem-6”;
const str = “Full Stack Developers”+sem;
• It is the before the plan of creating any objects which is known as the
blueprint of any objects which you want to create.
• In the ES6 to create any class, you need to use the class keyword.
ES6 Classes
Syntax :-
Class Class_name {
//class members
//constructors
//Methods
}
To use members and methods of this class we have to create an object .
Syntax to create an object is:
Syntax:-
Const Object_Name = new ClassName();
ES6 Classes
• The ES6 class also supports Inheritance.
• To Inherit a class extend keyword is used.
• The ES6 also support the concept of abstract classes.
ES6 Classes
Example:- class ParentClass{
doPrint() {
Example:- class Demo{ console.log("This doPrint() from Parent
// Constructor called.");
constructor(name, estd, rank) { }
this.n = name; }
this.e = estd; class ChildClass extends ParentClass {
this.r = rank; doPrint() {
} super.doPrint()
// Function console.log("This doPrint() is printing a
decreaserank() { string.");
this.r -= 1; }
} }
} var ChildClass = new ChildClass();
const d = new Demo(“Alice”, 2009, 43) obj.doPrint();
d.decreaserank(); Output:
Here rank will be decreased by 1. This doPrint() from Parent called.
This doPrint() is printing a string.
ES6 Objects and Arrays
• Objects and arrays :-
Both objects and arrays are considered “special” in JavaScript. Objects
represent a special data type that is mutable and can be used to store a
collection of data (rather than just a single value).
Arrays are a special type of variable that is also mutable and can also be used
to store a list of values.
ES6 Objects and Arrays
We can create arrays in two ways:
Syntax:-
var array_name = new Array(); // By using the new keyword
var array_name = [value1, value2,....valueN]; //By using Array literals o
OR
var array_name; //Declaration
array_name=[value1, value2,…..valueN]; //Initialization
ES6 Objects and Arrays
• Objects are the collection of key/value pairs that can be modified throughout the
lifecycle of an object as similar to hash map or dictionary.
• There are two syntaxes to create an empty object:
var user = {}; // 'object literal' syntax
var name = new Object(); //'object constructor' syntax
Example:-
//Creation of object
let user = {
user_name: ”Harry”,
Number: ”7676576567”
}
//Access the object value
Console.log(user.name);
Destructuring Assignment/Object Destructuring
• Destructuring assignment allows you to locally scope fields within an object
and to declare which value will be used.
• When destructuring the objects, we use keys as the name of the variable. The
variable name must match the property (or keys) name of the object.
• If it does not match, then it receives an undefined value. This is how JavaScript
knows which property of the object we want to assign.
• In object destructuring, the values are extracted by the keys instead of position
(or index).
• Let us understand object destructuring with some example,
Destructuring Assignment/Object Destructuring
• Example-1:- • Explanation :-
const num = {x: 100, y: 200}; • Here num is an object which has two keys x and y,
const {x, y} = num; Value of x is 100 and y is 200.
console.log(x); // 100 When we create variables x and y and pass the
object to that variable, value of x and y will be same
console.log(y); // 200
as value of keys of object num that is:
x = num.x
y = num.y
Destructuring Assignment/Object Destructuring
• Example-2:-
const student = {
name: 'Arun’,
position: 'First’,
rollno: '24'};
const {
name,
position,
rollno} = student;
console.log(name);// Arun
console.log(position);// First
1.console.log(rollno); // 24
Destructuring Assignment/Object Destructuring
• Example-3:- • The code pulls bread and cheese out of
const Sandwich = { the object and creates local variables for
them.
bread:”Dutch”,
• Also the bread and cheese variables can
cheese:”Swiss”, be changed:
Topping:”Lettuce” bread=“Garlic”;
}; cheese:”mozzarella”
const {bread,cheese}=Sandwich; Change in these two variables will not
Console.log(bread,cheese); effect the value of Sandwich object.
i.e. If we try to use Sandwich.bread the
value will be Dutch.
ES6 Promises
• Promises gives us a way to make sense out of asynchronous behavior.
• When making asynchronous request, one of two things can happen:
everything goes as we hope or there’s an error.
• Example: We could try several ways to obtain the data to reach success.
Or we could also receive multiple types of error.
• Promises gives us way to simplify back to simple pass or fail.
ES6 Promises
• The Promise represents the completion of an asynchronous operation. It
returns a single value based on the operation being rejected or resolved.
• There are mainly three stages of the Promise, which are shown below:
Importing a Module
To be able to consume a module, use the import keyword. A module can have
multiple import statements.
Introduction to React
• 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
● 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 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.
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
List Component in Reactjs
● Lists are used to display data in an ordered format and mainly used to
display menus on websites. In React, Lists can be created in a similar way
as we create lists in JavaScript.
● map() function is used for traversing the lists.
● Usually you would render lists inside a component.
}
function_name(parameter_list)
Functional Components
2) Call the function by using the functional component method.
e.g.:- function function_name()
{
}
<function_name/>
Class Component
• These components are simple classes (made up of multiple functions
that add functionality to the application). All class components are child
classes for the Component class of ReactJS.
E.g.:-
import React from "react";
render(){
return(
<div><h1>Hello{this.props.name}</h1></div>
)
}
}
Props
• Example:-//app.js
function App()
{
return(
<div>
<Person name=“rahul”/>
</div>
)
}
export default App;
Props
• Example :- Props in functional components.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return ( <div>
<Welcome name="Sara" />
<Welcome name="Cahal"/>
<Welcome name="Edite" />
</div> );
}
Class Component State
• The main feature of class components that distinguished them from
functional components is that they have access to a state which
dictates the current behavior and appearance of the component (Later,
with React Hooks introduced in version 16.8, we are able to declare a
stateful component without declaring a class).
• This state can be modified by calling the setState() function. One or
more variables, arrays, or objects defined as part of the state can be
modified at a time with the setState() function.
Class Component State
• Functional components are state-less.
• State is an in-built object.
• The state object is used to store all the data that belongs to that particular
component only.
• The data about class object is stored in states. It is private data that is not
accessible by other classes directly.
• To use state inside a class component “this.state” is used.
• To use state inside a functional component “useState” hook is used.
Class component state
• Example:-
• Class person extends Component
{
constructor(props){
super(props);
this.props=props;
this.state={ name:”Rahul”};
}
render(){
return(
<div><h1>Hello {this.state.name}</h1></div>
)
}
}
Class component state
• Example:-//app.js
function App()
{
return(
<div>
<Person/>
</div>
)
}
export default App;
Class component State
• If you want to change the value of current state than setState(object)
method is used.
• Eg. setState(name:”Rohit”)
Difference between Functional and Class Component
Functional Components Class Components
Constructors are not used . Constructor are used as it needs to store state.
React DOM
• React JS ReactDOM or react-dom is the most widely used package of
React. React provides the developers with a package react-dom to
access and modify the DOM. Let’s see in brief what is the need to have
the package.
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')
);
conditionals
● Your components will often need to display different things depending on
different conditions. In React, you can conditionally render JSX using
JavaScript syntax like,
● If
● Ternary operator (?)
● Short circuit operator (&&)
Conditionals
• If :-
• We can use the if JavaScript operator to decide which
component to render.
//App.js
Function App()
{
return ( <div> <Goal isGoal={true}/> </div> );
}
Conditionals
• Ternary Operator
Examxple:-function Goal(props) {
const isGoal = props.isGoal;
return ( <h1> { isGoal ? <MadeGoal/> :
<MissedGoal/> } </h1>
);
}
Conditionals
• Short circuit operator
Example:-
function Garage(props) {
const cars = props.cars;
return ( <> <h1>Garage</h1>
{cars.length > 0 && <h2> You have
{cars.length}
cars in your garage.
</h2>
}
</>
);
}
Handler functions in Reactjs
• Handling events with React elements is very similar to handling events on DOM
elements. There are some syntax differences:
• React events are named using camelCase, rather than lowercase.
• With JSX you pass a function as the event handler, rather than a string.
For Example :-
<button onclick=“Submit()"> Submit </button>
is slightly different in React:
<button onclick={Submit}> Submit </button>
This is the syntax to call a functional component.
Handler function in Reactjs
• While working with the classes it is different to handle events.
• For example:-
If you want to call a method of a class then you must call it by
using instance of class.
Handler Functions in Reactjs
class Toggle extends React.Component
{
constructor(props) {
super(props);
this.props=props
}
handleClick() {
//Some code
}
render() {
return ( <button onClick={this.handleClick}> Display</button> );
}
}
Handler functions in ReactJS
• Now, if I want my function to be called as a normal function, i.e. with some
parameters than following is the syntax for it.
• Example:-
• <button onClick={()=> this.handleClick()}> submit </button>
• We can also pass arguments to event handlers.
• Example:-
• <button onClick={()=> this.handleClick(“Ritu”)}> submit </button>
Single page application
• 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 application
Single page application
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.
Multi page application
Multi page application
• 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.
Multi page application
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.