Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
489 views

JavaScript PDF

React JS is a JavaScript library created by Facebook for building user interfaces. It allows developers to create reusable UI components that efficiently update and render via a virtual DOM. Some key points about React include: - It handles UI rendering with reusable components that contain data and behavior - The virtual DOM improves efficiency by only updating parts of the actual DOM that changed - React is a library rather than a framework, so projects using it are not fully dependent on React

Uploaded by

amitfegade121
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
489 views

JavaScript PDF

React JS is a JavaScript library created by Facebook for building user interfaces. It allows developers to create reusable UI components that efficiently update and render via a virtual DOM. Some key points about React include: - It handles UI rendering with reusable components that contain data and behavior - The virtual DOM improves efficiency by only updating parts of the actual DOM that changed - React is a library rather than a framework, so projects using it are not fully dependent on React

Uploaded by

amitfegade121
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

React JS

Pre-requisite:
--------------
1) Basic knowledge of JavaScript, HTML and CSS is required
2) ES6 new features.
3) Knowledge of Angular framework is advantage (optional)

Introduction:
-------------
1) It is a JavaScript library created by Facebook in 2011.
2) Every application is basically divided into 3 parts:
a) UI/Presentation Layer
b) Business Layer
c) Data Layer
3) React JS is a library used for creating UI.
4) It is used by Instagram and Netflix.
5) React - library - Only render the view and synch the
state of component.
6) Component - Main part of React JS.
7) A component is a piece of UI.
8) when we develop an application, we create a bunch of
independent isolated and reusable components, finally
combine all the components to create complex UI.
9) Used to create Single Page Applications (SPA)
10) We can build modern, fast Single Page Applications or
websites with React.

Q. Is React JS a Library or a Framework?


Ans: React is a Library, not a Framework.

Q. What is a Library?
-- A library in programming can be explained as a collection
of codes. We use a library to write code in a much
simpler way or to import a feature from it into our
project.
-- For e.g. jQuery is a library.
-- We can write JavaScript much simpler by using jQuery, or
we can import written jQuery features to our project.
The project itself is not dependent on a library.
Q. What is a Framework?
-- A Framework, on the other hand, is a complete package of
code with its own functionalities & libraries.
-- A framework has its own rules, you don’t have much
flexibility and the project is dependent on the framework
you use.
-- Angular is an example of a framework.

How React actually works?


-------------------------
React Virtual DOM:

• To understand the importance of React Virtual DOM, first,


you need to know what DOM (Document Object Model) is.
• DOM is basically the representation of the HTML code in a
webpage. The document is the webpage itself, the objects
are the HTML tags. And finally, the model of DOM is a tree
structure:

What is the benefit of Virtual DOM?

• Each time you make a change in the code, DOM will be


completely updated and rewritten. This is an expensive
operation and consumes lots of time. In this point, react
provides a solution: The Virtual DOM.
• So when something changes:
1. React first creates an exact copy of the DOM
2. Then React figures out which part is new and only
updates that specific part in the Virtual DOM
3. Finally, React copies only the new parts of the
Virtual DOM to the actual DOM, rather than completely
rewriting it.
4. This approach makes a webpage much faster than a
standard webpage. That’s also one of the reasons why
React is so popular.

Software required:
-------------------

1) NodeJS
2) Visual Studio Code.

Setup development environment:


------------------------------

> npm install -g create-react-app

[We install this package to setup our react project]

> create-react-app <project-name>


> create-react-app hello-world

OR

> npx create-react-app hello-world

(npx - node package runner)

-- Once application is ready, we can run our application using:

> npm start

-- We can access our application on browser:

http://localhost:3000

Some concepts of JavaScript that you should know before learning React:
-----------------------------------------------------------------------

1) var vs let vs const


2) Objects in JavaScript
3) this keyword
4) bind() method
5) Arrow functions
Arrow Functions and "this" keyword
6) Arrays.map() method
7) Object Destructuring
8) spread operator
9) Classes
10) Inheritance

1) let vs var vs const


-----------------------

function sayHello() {
for(var i = 0; i < 5; i++) {
console.log(i);
}
}
sayHello();

scope of variable - block in which variable is accessible.


Modify the above function

function sayHello() {
for(var i = 0; i < 5; i++) {
console.log(i);
}
console.log(i)
}
sayHello();

var - If we define variable with the var keyword, then that variable
will be accessible inside the function in which it is defined.

ES6/ES2015 - Introduced let keyword.

function sayHello() {
for(let i = 0; i < 5; i++) {
console.log(i);
}
console.log(i); //will get an error here.
}

sayHello();
var -> scope - function
let -> scope - block

ES6 - const keyword.

const -> block scope - can't change the value.

const x = 1;
x = 2; //error here x is read-only.

2) Objects:
-----------

Objects in JavaScript are collection of key-value pairs.

const person = {
name: "Alex",
age: 34,
walk() {},
run: function() { }
}

console.log(person.name)
person.walk()
person.run()
console.log(person['age'])

3) this keyword:
----------------

const person = {
name: "Alex",
age: 31,
walk() {
console.log(this);
}
}

person.walk();
case 2:
-------

const person = {
name: "Alex",
age: 31,
walk() {
console.log(this);
}
}

walk = person.walk; //assigning reference of walk() function.


walk();

Note: output of "this" depends on how we call the function.


• If we call a function as method in an object, this always refer
to that object.
• If we call a function as a standalone object or outside of an
object, this refers to global object i.e. window object of
browser.
• If we call, walk() function on person object, this refers to
person object.

4) bind() method:
-----------------

How we can fix the problem of "this" keyword?

• Functions are objects in JavaScript.


• One of the methods is bind() method. Use of this method is to
bind the function to an object.
• walk = person.walk.bind(person);

Complete Example
-----------------

const person = {
name: "Alex",
age: 31,
walk() {
console.log(this);
}
}
walk = person.walk.bind(person); //assigning reference of walk()
//function.
walk();

• person.walk.bind(person) will return new instance of a walk()


function and set "this" to point to person object.

5) Arrow functions:
-------------------

const square = function(number) { // Regular function


return number * number;
}

const square = number => number * number; // Arrow function

square(5); // calling a function

const jobs = [
{id: 1, isActive: true},
{id: 2, isActive: true},
{id: 3, isActive: false}
]

Find all active jobs.

const activeJobs = jobs.filter(function(job) {


return job.isActive;
})

const activeJobs = jobs.filter(job => job.isActive);

-----------------------------------
Arrow functions and "this" keyword:
-----------------------------------

• Arrow functions don't rebind "this". Arrow functions inherit


"this".
const person = {
name: "Alex",
age: 32,
walk() {
console.log("this", this);
}
}
person.walk();

Modify the above code:


----------------------

const person = {
name: "Alex",
age: 32,
walk() {
setTimeout(function() {
console.log("this", this);
}, 1000)
}
}
person.walk(); //output: window object.

• This callback function is not a part of any object, that's why


"this" refers to window object.
• It is a standalone function.

How to solve this problem? How can I get reference to person object
in callback function?
--------------------------------------------------------------------

Old way:
--------

const person = {
name: "Alex",
age: 32,
walk() {
var self = this;
setTimeout(function() {
console.log("self", self); // this -> person object
}, 1000)
}
}
person.walk();
New way: use arrow functions
----------------------------

const person = {
name: "Alex",
age: 32,
walk() {
setTimeout(() => {
console.log("this", this); // this -> person object
}, 1000)
}
}
person.walk();

Note: Arrow functions inherit "this" keyword.

Let's summarize:
----------------

1) const person = {
name: "Alex",
age: 32,
walk() { // Regular function
console.log(this); // person object
}
}

person.walk(); // output: person object

2) const person = {
name: "Alex",
age: 32,
walk() {
setTimeout(function() {
console.log("this", this); // window object
}, 1000);

console.log(this); // this refers to person object


}
}
person.walk();
3) const person = {
name: "Alex",
age: 32,
walk() {
var self = this; // assigning this (person object)
// to self.
setTimeout(function() {
console.log("this", self); //self -> person object
}, 1000);

console.log(this); // this refers to person object


}
}
person.walk();

4) const person = {
name: "Alex",
age: 32,
walk() {
//inside walk(), this ----> person object
// person object [using arrow function]

setTimeout(() => console.log("this", this), 1000);

console.log(this); // this refers to person object


}
}
person.walk();

5) const person = {
name: "Alex",
age: 32,
walk: () => {
console.log(this); //window object
}
}
person.walk();

6) Arrays.map() method:
-----------------------
• ES6 introduced new method Arrays.map()
• We will use this method in React to iterate List.
const names = [“Alex”, “Anna”, “Bob”, “Jason”];
const names2 = names.map(function(name) {
return “<li>” + name + “</li>”;
})
console.log(names2);

• We have to pass callback function in map() method.


• Job of callback function is to transform each element of
an array.
• Callback function is called by map() function for each
item in an array. It takes one item at a time and returns
new item.
• map() function doesn’t modify original array. It returns
new array.
• We can also implement callback function by using arrow
functions.

const names2 = names.map(name => return “<li>” + name + “</li>”)

OR

• We can also use ES6 template literals.


• ` - backtick character (under escape key)

const names2 = names.map(name => return `<li>${name}</li>`)

• ${name} – argument placeholder. It renders the name


dynamically at runtime.

7) Object DE structuring:
-------------------------

const address = {
street: "677 Tanglewood Road",
city: "Rolling Fork",
state: "Mississipi",
zipcode: 39159
}

const street = address.street;


const city = address.city;
const state = address.state;
const zipcode = address.zipcode;
const { street, city, state, zipcode } = address;

-- You can also extract few properties

const { street, city } = address;

-- You can also provide an alias

const { zipcode: zip } = address;

8) spread operator (…):


-----------------------
even_numbers = [2, 4, 6, 8, 10];
odd_numbers = [1, 3, 5, 7, 9];

Now I want to concatenate these 2 arrays.

const numbers = even_numbers.concat(odd_numbers);

const numbers = […even_numbers, …odd_numbers];

const numbers = […even_numbers, 34, …odd_numbers, 56];

Cloning of an array:
--------------------
const even_numbers_clone = […even_numbers]

We can also use spread operator with objects.

first = { name: "Alex" }


second = { age: 21 }

const combined = {…name, …second, job: "Instructor" };

const clone = {…first} //cloning an object

9) classes:
-----------

const person1 = {
name: "Alex",
age: 31,
walk() {
console.log("walk");
}
}

const person2 = {
name: "Anna",
age: 31,
walk() {
console.log("walk");
}
}

Problems:
---------
• walk() method code is duplicated.
• What else if we want to modify walk() method, we have to
modify in every object.

Solution:
---------
• Create class (blueprint/template)

class Person {
constructor (name, age) {
this.name = name;
this.age = age;
}
walk() {
console.log("walk");
}
}

Create objects:
---------------
const person1 = new Person("Alex", 31);
const person2 = new Person("Anna", 34);

console.log(person1.name + " – " + person1.age);


person1.walk();

10) Inheritance:
----------------

class Teacher extends Person {


teach() {
console.log("teach");
}
}

const teacher = new Teacher("Bob", 34);


console.log(teacher.name + " - " + teacher.age);
teacher.walk();
teacher.teach();

• What if we want to add new property in Teacher class

class Teacher extends Person {


constructor(name, age, degree) {
super(name, age); //Mandatory else will get an error
this.degree = degree;
}
teach() {
console.log("teach");
}
}

const teacher1 = new Teacher ("Jason", 32, "BE");


console.log(teacher1.name + "- " + teacher1.age + " - " +
teacher1.degree);
teacher1.walk();
teacher1.teach();

Note: Whenever we define constructor in child class, super() is


compulsory else we will get an error.

11) modules:
------------
• Instead of writing all code inside one file, we split the
code into multiple files, this is called as "Modularity".
• Each file is called as "module".
• Let’s modularize our previous code.
person.js
----------
export class Person {
constructor (name, age) {
this.name = name;
this.age = age;
}
walk() {
console.log("walk");
}
}

teacher.js
----------
import { Person } from "./person.js";

export class Teacher extends Person {


constructor(name, age, degree) {
super(name, age); //Mandatory else will get an error
this.degree = degree;
}
teach() {
console.log("teach");
}
}

main.js
-------
import { Teacher } from "./teacher.js";

const teacher1 = new Teacher ("Jason", 32, "BE");


console.log(teacher1.name + "- " + teacher1.age + " - " +
teacher1.degree);
teacher1.walk();
teacher1.teach();

Note: By default, objects defined inside the module are


Private. We have to make them public so that they can
be accessible inside other modules.
We can make those objects public by exporting them.

Named and default exports:


--------------------------

A module can have more than one object inside it.


Let’s add promote() method inside Teacher class.

teacher.js
----------
import { Person } from "./person.js";

export function promote() {}

export class Teacher extends Person {


constructor(name, age, degree) {
super(name, age); //Mandatory else will get an error
this.degree = degree;
}
teach() {
console.log("teach");
}
}

main.js
-------
import { Teacher, promote } from "./teacher.js";

const teacher1 = new Teacher ("Jason", 32, "BE");


console.log(teacher1.name + "- " + teacher1.age + " - " +
teacher1.degree);
teacher1.walk();
teacher1.teach();
promote();

• Let’s look at an example of default export.

import { Person } from "./person.js";

export function promote() {}

export default class Teacher extends Person {


constructor(name, age, degree) {
super(name, age); //Mandatory else will get an error
this.degree = degree;
}

teach() {
console.log("teach");
}
}

• In our example, we have used default export for Teacher


class.

main.js
-------
import Teacher, { promote } from "./teacher.js";

const teacher1 = new Teacher ("Jason", 32, "BE");


console.log(teacher1.name + "- " + teacher1.age + " - " +
teacher1.degree);
teacher1.walk();
teacher1.teach();
promote();

Note: A module can have at most one default export but can
multiple named exports.

Default exports: import … from "<module>";

Names exports: import { … } from "<modules";

JSX

• In classic Frontend programming, we have separated HTML,


CSS and JS file structures. React is a bit different. We
don’t have separated HTML files in React.
• In JSX syntax, we write HTML tags inside JavaScript.
• A syntax extension for JavaScript, written to be used with
React.
• JSX is not valid JavaScript & web browsers cannot read it.
• If a JavaScript file contains JSX code, then that file
needs to be compiled, which means that before the file
reaches a web browser, a JSX compiler will translate any
JSX into regular JavaScript.
• JSX produces React elements.

Babel:
• A transpiler for JavaScript best known for its ability to
turn ES6 (the next version of JavaScript) into code that
runs in a browser.
• Created by an Australian developer named Sebastian
McKenzie
• Can handle all of the new syntax that ES6 brings, along
with built-in support for React’s JSX extensions
• Has the greatest level of compatibility with the ES6
specifications.
• Let’s you use virtually all new features of ES6, without
sacrificing backward compatibility for older browsers.

Understanding JSX:

• A basic unit of JSX is called a JSX element


• JSX elements must be a part of a .js file
• JSX elements are treated as JavaScript expressions.
• In React, for example, a simple JavaScript variable can
be like this:
const element = <h1>Hello!</h1>;
• Normally, we can’t assign an HTML tag to a JavaScript
variable. But with JSX, we can. The code above you see is
neither HTML nor JavaScript. It’s an example of JSX.

Do I have to work with JSX?

• You don’t have to use JSX with React, but it is strongly


recommended.
• JSX simplifies React and makes it easier to read.

You might also like