An Introduction to ReactJS, A JS Library for building user interfaces developed by Facebook Team, also this presentation introduce what is the ReduxJS Library and how we can use it with ReactJS.
3. ReactJS:
History, What, Why, How it works?
Environment
Component
Functional & Class Components
Component Lifecycle
Handling Events
Conditional Rendering
Render List
Form
Communication
External Data
Routing
Extensions
File Structure
Tips & Tricks.
Agenda
JS History.
ES6 Basics For ReactJS.
Recommended Books.
Web Components.
Component Architecture.
SPA.
4. Browsers War.
Netscape, 1995.
Scheme in browser.
Java.
Scheme, Self and Java.
10 days!
Mocha, LiveScript and JavaScript.
ECMAScript.
A brief history of JS
6. ES6 – ECMAScript 2015
Modules, Import and Export
Arrow functions
Constructor functions
Classes and Extends
Bind, apply, call
Var, let and const
Template Literals – Back-tick
Object Destructuring
Default, Rest and Spread
7. ES6 – ECMAScript 2015 – Cont.
Modules, Import and Export
Modular programming is used to break large applications into smaller blocks of manageable code.
Module based coding eases the effort for maintenance and increases reusability.
8. ES6 – ECMAScript 2015 – Cont.
Modules, Import and Export
ES5
Modules at ES5
9. ES6 – ECMAScript 2015 – Cont.
Modules, Import and Export
ES5
Modules at ES5
10. ES6 – ECMAScript 2015 – Cont.
Modules, Import and Export
ES5
Modules with libraries, CommonJS and RequireJS(AMD)
OR
11. ES6 – ECMAScript 2015 – Cont.
Modules, Import and Export
ES5
Modules with libraries, CommonJS and RequireJS(AMD)
12. ES6 – ECMAScript 2015 – Cont.
Modules, Import and Export
ES6
Modules at ES6
OR
14. ES6 – ECMAScript 2015 – Cont.
Arrow functions
ES6
With ECMAScript 2015, JavaScript got arrow functions, which are mainly syntactic sugar for defining function
expressions and does not have its own this, arguments, super or new.target.
These function expressions are best suited for non-method functions, and they cannot be used as
constructors.
18. ES6 – ECMAScript 2015 – Cont.
Classes and Extends
ES6
JavaScript classes, introduced in ECMAScript 2015
Syntactical sugar over JavaScript's existing prototype-based inheritance.
The class syntax does not introduce a new object-oriented inheritance model to JavaScript.
Classes support static methods so you can called without instantiating their class and cannot be called through a
class instance.
The extends keyword is used in class declarations or class expressions to create a class as a child of another class.
The super keyword is used to call corresponding methods of super class.
19. ES6 – ECMAScript 2015 – Cont.
Classes and Extends
ES6
// stephen hawking
// Hi Neil Person
// Hi Neil astrophysicist
// Hello Neil Person
20. ES6 – ECMAScript 2015 – Cont.
Bind, Apply, Call and of course ‘THIS’
ES3/ES5
Functions can be used in many different contexts, and they need to be able to work in each
situation. Even though this is typically assigned automatically, you can change its value to achieve
different goals.
There are three function methods that allow you to change the value of this.
Remember that functions are objects, and objects can have methods, so functions can, too.
21. ES6 – ECMAScript 2015 – Cont.
Bind, Apply, Call and of course ‘THIS’
ES3/ES5
// Family Name(Call) : Tyson
// My Family Name(Call) : Hawking
// Family Name(Apply) : Tyson
// My Family Name(Apply) : Hawking
// Family Name(Bind) : Tyson
// My Family Name(Bind) : Hawking
22. ES6 – ECMAScript 2015 – Cont.
Var, let
ES5/ES6
var vs let
Scope essentially means where these variables are
available for use. var declarations are globally scoped or
function/locally scoped.
It is globally scoped when a var variable is declared
outside a function.
var is function scoped when it is declared within a
function. This means that it is available and can be
accessed only within that function.
let is block scoped { }
23. ES6 – ECMAScript 2015 – Cont.
const
const
const declarations are block scoped
const cannot be updated or re-declared
ES6
24. ES6 – ECMAScript 2015 – Cont.
ES6
Template literals are string literals allowing embedded expressions. You can use multi-line strings and
string interpolation features with them.
Template Literals – Back-tick
25. ES6 – ECMAScript 2015 – Cont.
ES6
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values
from arrays, or properties from objects, into distinct variables.
// ["The Universe in a Nutshell", "On the Shoulders of Giants"]
Object Destructuring
26. ES6 – ECMAScript 2015 – Cont.
ES6
Default function parameters allow formal parameters to be initialized with default values if no value or
undefined is passed.
Default
27. ES6 – ECMAScript 2015 – Cont.
ES6
The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
Rest
28. ES6 – ECMAScript 2015 – Cont.
ES6
Spread syntax allows an iterable such as an array expression or string to be expanded in places where
zero or more arguments (for function calls) or elements (for array literals) are expected, or an object
expression to be expanded in places where zero or mor
Spread
29. ES6 – ECMAScript 2015 – Cont.
BabelJS
ES6
* Polyfill is code that implements a feature on web browsers that do not support the feature
*
30. Useful Books
The Good Parts 1st Edition by Douglas Crockford
The Principles of object-oriented javascript - by Nicholas C. Zakas
You don’t know JS by Kyle Simpson
ES6 – ECMAScript 2015 – Cont.
Books
33. Web Components
Web Components is a suite of different technologies allowing you to create reusable custom elements — with their
functionality encapsulated away from the rest of your code — and utilize them in your web apps.
Four main technologies
Custom elements.
<Galaxy /> and register this custom tag so you can use it with your document.
Shadow DOM.
Attaching an encapsulated "shadow" DOM tree to an element.
Resolve CSS Rules Problem for example.
HTML templates.
<template>
HTTML imports.
Example: <link rel="import" href="myfile.html">
34. Web Components
The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in
web components
Browser support
Not all browsers support this feature yet
Polymer 2.0
webcomponents.org
36. Component Architecture
A method for encapsulating individual pieces of a larger user interface (aka components) into self-
sustaining, independent micro-systems.
Components have their own structure, their own methods and their own APIs.
Components are also reusable and can be “pasted” into interfaces at will.
The independent nature of components allows for developers to create a UI with many different
moving parts.
Components each have their own interfaces that can make calls to the server and update their
interfaces.
Separation of Concern Component, MVC splits responsibilities horizontally, CBA splits them vertically.
39. SPA – Single-Page Application
Single-Page Applications (SPAs) are Web apps that load a single HTML page and dynamically
update that page as the user interacts with the app.
SPAs use AJAX and HTML5 to create fluid and responsive Web apps, without constant page
reloads.
This approach avoids interruption of the user experience between successive pages, making the application
behave more like a desktop application.
Just HTML, JavaScript, and CSS.
JavaScript frameworks (ReactJS, AngularJS, EmberJS, VueJS and so on)
Ajax
Websockets
Browser History
40. SPA – Single-Page Application
Traditional Page Lifecycle
In a traditional Web app, every time
the app calls the server, the server
renders a new HTML page. This
triggers a page refresh in the
browser. If you’ve ever written a
Web Forms application, this page
lifecycle should look familiar.
Page
Reload
Initial Request
HTML
Form Post
HTML
Client Server
41. SPA – Single-Page Application
SPA Lifecycle
In an SPA, after the first page loads,
all interaction with the server
happens through AJAX calls. These
AJAX calls return data—not
markup—usually in JSON format.
The app uses the JSON data to
update the page dynamically,
without reloading the page.
Initial Request
HTML
Ajax
JSON
Client Server
{…}
44. <UserCard user={cosmologist} />
/* Time to React */
const cosmologist = {
name: 'Neil Tyson',
imgURL: 'https://www.thefamouspeople.com/profiles/images/neil-degrasse-tyson-2.jpg'
}
45. React
History
Created by Jordan Walke, a software engineer at Facebook.
He was influenced by XHP, an HTML component framework for PHP.
Allow XML syntax for the purpose of creating custom and reusable HTML elements.
FaxJS
Facebook 2011, Instagram 2012 and open-sourced 2013.
16.3.2 Called React Fiber.
React Native 2015.
46. React
What?
React is a JS library Building interactive user interfaces.
So it is a View JS Library
React can be used to create SPA and mobile applications.
Still maintained by Facebook.
Not a Framework it is just a Library.
React is often used in conjunction with other libraries such as Redux or Flux.
47. React
Component-Based, Reusable Components.
Unidirectional data flow.
Not templates to create.
Work with any stack or framework.
Native
Declarative not Imperative
Easy to learn
Facebook
Why?
50. React
How it works?
Two-way Data Binding
Model View
Change to the VIEW
Update the MODEL
Change to the MODEL
Update the VIEW
51. React
How it works?
Dispatcher
Store/StateView
Single Source of Truth.
Provides predictable application state.
Much easier to pinpoint where the error
lies, as data follows a strict pipeline
React is a Unidirectional-Data Binding
Bind Data
Update storeDispatch Action
52. React
How it works?
DOM stands for Document Object Model and is an abstraction of a structured text. For web
developers, this text is an HTML code, and the DOM is simply called HTML DOM.
So, while HTML is a text, the DOM is an in-memory (tree-structured) representation of this text.
1. Browser have to parses the HTML
2. It removes the child element of elementId
3. Updates the DOM with the “New Value”
4. Re-calculate the CSS for the parent and child
5. Update the layout i.e. each elements exact co-ordinates on the screen
6. Traverse the render tree and paint it on the browser display
DOM
53. React
How it works?
Virtual DOM
Virtual DOM is in-memory representation of Real DOM. It is lightweight JavaScript object
which is copy of Real DOM.
Updating virtual DOM in ReactJS is faster because ReactJS uses
1. Diff algorithm, compares both the Virtual DOM to find the minimum number of steps to
update the Real DOM.
2. Batched update operations.
3. Efficient update of sub tree only.
4. Uses observable instead of dirty checking to detect change.
ReactJS maintains two virtual DOM, one with the updated state Virtual DOM and other with the
previous state Virtual DOM.
56. React
How it works?
JSX
This funny tag :D syntax is neither a string nor HTML.
JSX may remind you of a template language, but it comes with the full power of JavaScript.
JavaScript XML
React doesn’t require using JSX, but most people find it helpful as a visual aid when working
with UI inside the JavaScript code. It also allows React to show more useful error and warning
messages.
Embedding Expressions in JSX, Like Razor engine for example.
58. React
How it works?
JSX
Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming
convention instead of HTML attribute names.
For example, class becomes className in JSX, and tabindex becomes tabIndex.
61. React
How it works?
React-DOM
React and ReactDOM were only recently split into two different libraries.
From 0.14 and up.
ReactDOM is the glue between React and the DOM.
Use it for one single thing: mounting with ReactDOM.render().
Another useful feature of ReactDOM is ReactDOM.findDOMNode() which you can use to gain
direct access to a DOM element.
63. React
Recap
What are the elements that I can render them?
Strings.
Components or HTML tags.
Array of Strings, Components or HTML tags
How to create React Element?
Using JSX Syntax
Note: Don’t forget to wrap the elements with a container
69. React
React Component
Components let you split the UI into independent, reusable pieces, and think about each
piece in isolation.
Like JavaScript functions.
Accept any types and any numbers of properties ‘props’.
React elements describing what should appear on the screen
Two ways to define a component
Functional Component
Class Component
71. React
React Component Properties - Props
Component Properties – Props
Can be anything (string, number, array, simple object, complex object).
Props are Read-Only (immutable).
Can have default values (static defaultProps).
Can be validated at runtime (PropTypes).
Top-Down, Parent can send whatever prop values it likes to a child, but the child cannot
modify its own props.
72. React
React Component State
As Component has props, component has state.
You can consider that "state" is a database in object shape.
The heart of every React component (Statefull).
Determines how that component renders & behaves.
Private and fully controlled by the component.
You can add initial values to the state.
State cannot modified directly.
Only with SetState(nextState, callback) function
State Updates May Be Asynchronous
State Updates are Merge
73. React
React Component State
SetState(nextState, callback)
React may batch multiple setState() calls into a single update for performance.
It Rerender the whole component,
The parent one and all children of this parent.
Whenever setState() method is called, ReactJS creates the whole Virtual DOM from scratch. Creating a
whole tree is very fast so it does not affect the performance
75. React
Functional Component vs Class Component
Functional vs Class
Receive parameter (Props) - Optional
Stateless or dumb component.
Just Plain old JavaScript functions.
Shorter to write
For UI Components
Has local State
Receive parameter (Props) - Optional
Statefull or smart component
Has Lifecycle hooks.
Can Handles fetching data via ajax calls
76. React
Component Lifecycle
The Component Lifecycle
Each component has several “lifecycle methods” that you can override to run code at particular times
in the process.
Methods prefixed with will are called right before something happens, and methods prefixed
with did are called right after something happens.
78. React
Component Lifecycle
componentWillMount
render
componentDidMount
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidupdate
componentWillUnmount
Immediately before initial rendering
Render the elements.
Immediately after initial rendering
When component receives new props
Before rendering, after receiving news props or state.
Before rendering, after receiving news props or state.
After component's updates are flushed to DOM.
Immediately before removing component from DOM.
79. React
Component Lifecycle – Phase 1
Initialization
In this phase the React setting up the initial states
and default props, if any.
The component is setting up the initial state in
the constructor, which can be changed later by
using the setState method.
The defaultProps is defined as a property of
Component to define all the default value of
props, which can be overridden with new prop
values.
80. React
Component Lifecycle – Phase 2
Mounting
React Component now is ready to mount in the browser
DOM.
This phase gives hook methods for before and after
mounting of components.
• componentWillMount is executed just before the
React Component is about to mount on the DOM.
• render mounts the component onto the browser.
• componentDidMount this is the hook method which is
executed after the component did mount on the
DOM.
81. React
Component Lifecycle – Phase 3
Updating - Props
This phase starts when the react component has
taken birth on the browser and grows by receiving
new updates.
Can be updated by two ways, sending new props or
updating the state.
componentWillReceiveProps gets executed when
the props have changed and is not first render.
Usage: This is how the state can be kept synced with
the new props.
82. React
Component Lifecycle – Phase 3 - cont
Updating - Props
shouldComponentUpdate tells the React that when
the component receives new props or state is being
updated, should React re-render or it can skip
rendering?
Enhance performance of a slow component
83. React
Component Lifecycle – Phase 3 - cont
Updating - Props
componentWillUpdate is executed only after the
shouldComponentUpdate returns true. This method
is only used to do the preparation for the upcoming
render, similar to componentWillMount or
constructor.
84. React
Component Lifecycle – Phase 3 - cont
Updating - Props
componentDidUpdate is executed when the new
updated component has been updated in the DOM.
This method is used to re trigger the third party
libraries used to make sure these libraries also
update and reload themselves.
85. React
Component Lifecycle – Phase 4
Unmounting
componentWillUnmount This method is the last
method in the lifecycle. This is executed just before
the component gets removed from the DOM.
Usage: In this method, we do all the cleanups
related to the component.
86. React
Component Lifecycle
So
Don’t use setState with
constructor
componentDidMount, and will cause a performance issue.
componentWillUpdate, would trigger an update to a React component before
componentWillUpdate() returns
87. React
Component Lifecycle – Other Hooks
forceUpdate()
Calling forceUpdate() will cause render() to be called on the component, skipping
shouldComponentUpdate(). This will trigger the normal lifecycle methods for child components,
including the shouldComponentUpdate() method of each child. React will still only update the DOM if
the markup changes.
Normally you should try to avoid all uses of forceUpdate() and only read from this.props and
this.state in render().
componentDidCatch(error, info)
catch JavaScript errors anywhere in their child component tree, log those errors, and display a
fallback UI instead of the component tree that crashed.
Calling setState() in it lets you capture an unhandled JavaScript error in the below tree and display a
fallback UI.
88. React
Component Lifecycle – Diagrams
Component Creation Steps
render
constructor
componentWillMount
create and render all direct
child components
componentDidMount
A New Props Received
componentWillUpdate
componentWillReceiveProps
render
componentDidUpdate
shouldComponentUpdate
stop
true false
setState
componentWillUpdate
render
shouldComponentUpdate
stop
true false
Send new props to all
direct child components
componentDidUpdate
Send new props to all
direct child components
89. React
Handling Events
Handling events with React elements is very similar to handling events on DOM elements.
There are some syntactic differences:
React events are named using camelCase, rather than lowercase.
With JSX you pass a function as the event handler, rather than a string.
You cannot return false to prevent default behavior in React. You must call preventDefault explicitly.
90. React
Handling Events
The BIND
In JavaScript, class methods are not bound by default
If you forget to bind this.onHandleClick and pass it to onClick, this will be undefined when the
function is actually called
92. React
Conditional Rendering
In React, you can create distinct components that encapsulate behavior you need. Then, you
can render only some of them, depending on the state of your application.
It is all about if, else, switch statements and conditional (ternary) - ? : - operator.
Logical && Operator
Logical || Operator
To Prevent a component from rendering just return null.
94. React
How to render a List
As we said before, What are the elements that I can render them?
Strings.
Components or HTML tags.
Array of Strings, Components or HTML tags.
Must be An Array
creates a new array with the
results of calling a provided
function on every element in
the calling array.
95. React
How to render a List
A “key” is a special string attribute you need to include when creating lists of elements.
Keys help React identify which items have
changed, are added, or are removed.
Keys should be given to the elements
inside the array to give the elements a
stable identity.
Keys Must Only Be Unique Among
Siblings
97. React
Form
HTML form elements work a little bit differently from other DOM elements in React, because
form elements naturally keep some internal state.
Controlled components, input form element whose value is controlled by React
In HTML, form elements such as <input>, <textarea>, and <select> typically maintain their
own state and update it based on user input. In React, mutable state is typically kept in the
state property of components, and only updated with setState().
We can combine the two by making the React state be the “single source of truth”
100. React
Form - cont
Uncontrolled components, where form data is handled by the DOM itself.
To write an uncontrolled component, instead of writing an event handler for every state update, you
can use a ref to get form values from the DOM.
When to use refs?
Managing focus, text selection, or media playback.
Triggering imperative animations.
Integrating with third-party DOM libraries Like Jquery.
102. React
Communication
Shared State (Lifting state up)
Shared a state between two components.
Removing the local state from the descendant component and move
it into its ancestor instead.
When we update an input, an other component should reflect the
change (and vice versa).
Remember: single source of truth
ancestor
descendants
Lifting State Up
107. React
Redux
Redux
Motivation
Lost control over the when, why, and how of its state.
Single Source of truth is to hard to maintain.
Hard to reproduce bugs or add new features.
Handle optimistic updates, server-side rendering, fetching data before performing route transitions will be
impossible.
110. React
Redux
Main Concepts
Like React, Redux guarantee that data will be updated via Unidirectional data-binding
technique.
So to update the state and it called Store at Redux, you need to
Dispatch an action to update a portion at the store and it called Action Creator
Action Creator return plain JS object called Action Object that describes what happened.
Enforcing that every change is described as an action lets us have a clear understanding of what’s
going on in the app.
Okay, to tie the state (store) with the action creators we need a function that handle the checks
and this function we called it (Reducer).
Every time when you dispatches an action, store will broadcast this action to all the reducers
(including its sub-reducers). and if the action.type matches, then the reducer will handle this action
accordingly.
111. React
Redux
Three Principles
Single source of truth.
State is read-only.
The only way to change the state is to emit an action, an object describing (action.type) what
happened.
This ensures that neither the views nor the network callbacks will ever write directly to the state.
Changes are made with pure functions
Reducers are just pure functions that take the previous state and an action, and return the next state.
112. React
Redux Workflow
Action Creator
UI
Dispatch
Calculate and
return new store
Redux
Broadcast The
Action Object and
the current store
Reducer
Reducer
Reducer
Reducer
ReduxStore
Send the new
store to save it
Send Action
Object
Send the new
state for
updating
113. React
Redux
Action Creators & Actions
Actions are payloads of information that send data from your application to your store.
The only source of information for the store.
You send them to the store using store.dispatch() as it dispatch Action Creator.
114. React
Redux
Reducer
Specify how the application's state changes in response to actions sent to the store.Normal (Pure)
function
Computes only the new state.
Should be completely predictable: calling it with the same inputs many times should produce the
same outputs.
Shouldn't perform any side effects like API calls or router transitions.
You cannot update in state directly, you create a new object using Object.assign({}, state) then return it and the
redux will handle how to update the store.
You can split the reducer to sub-reducers to so you can maintain it easily then you can combine them
116. React
Redux
Store
You'll only have a single store in a Redux application.
If You want to split your data handling logic, you'll use reducer composition instead of many stores.
New Reducer = New Store
The store has the following responsibilities:
Holds application state;
Allows access to state via getState();
Allows state to be updated via dispatch(action)
118. React
Redux – Advanced Topics -Middleware
Middleware
Redux middleware is nothing more than a function which is invoked after an action is dispatched
but before a reducer takes care of the action.
Middleware are functions that allow us extend the functionality of our redux application.
119. React
Redux – Advanced Topics -Middleware
Broadcast The
Action Object and
the current store
Re
n Creator
Send Action
Object
Reduc
Middleware#1
Middleware#2
Middleware#3
Middleware#4
126. React
Routing
Components are the heart of React's powerful, declarative programming model.
React Router is a collection of navigational components that compose declaratively with your
application.
Work with Web Application and React Native.
https://en.wikipedia.org/wiki/Browser_wars
https://en.wikipedia.org/wiki/Brendan_Eich
https://en.wikipedia.org/wiki/JavaScript
https://en.wikipedia.org/wiki/ECMAScript
http://2ality.com/2011/03/javascript-how-it-all-began.html
https://www.coursera.org/learn/javascript-jquery-json/lecture/h5d03/bonus-brendan-eich-inventing-javascript
https://www.w3schools.com/js/js_versions.asp
http://blog.hamedfarag.com/post/2016/09/13/%D8%AA%D8%A7%D8%B1%D9%8A%D8%AE-%D8%A7%D9%84%D8%AC%D8%A7%D9%81%D8%A7-%D8%B3%D9%83%D8%B1%D9%8A%D8%A8%D8%AA
(1)Using the basic syntax of C language, (2)Using Java language data types and memory management, (3)Using Scheme language, ascension will function to the "first citizen" (first class) status, (4)Using Self language, the use of prototype based inheritance mechanism (prototype).
IIFE
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
Encapsulation
First Class Object
https://www.c-sharpcorner.com/article/first-class-function-in-javascript/
Pass as parameter.
Return the function from another function.
Assign a function to a variable.
Assign to a property at object.
Function can have the properties.
https://stackoverflow.com/questions/705173/what-is-meant-by-first-class-object?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
var calculator = (function () {
var _add = function (a, b) { return a + b; }
var _subtract = function (a, b) { return a - b; }
var _multiply= function (a, b) { return a * b; }
var _divide = function (a, b) { return a / b; }
return {
add: _add,
subtract: _subtract,
multiply: _multiply,
divide: _divide
}
}())
var main = (function(calculator){
console.info(calculator.add(1, 3));
}(calculator));
https://auth0.com/blog/javascript-module-systems-showdown/
PROS
Simple enough to be implemented anywhere (no libraries, no language support required).
Multiple modules can be defined in a single file.
CONS
No way to programmatically import modules (except by using eval).
Dependencies need to be handled manually.
Asynchronous loading of modules is not possible.
Circular dependencies can be troublesome.
Hard to analyze for static code analyzers.
var calculator = (function () {
var add = function (a, b) { return a + b; }
var subtract = function (a, b) { return a - b; }
var multiply= function (a, b) { return a * b; }
var divide = function (a, b) { return a / b; }
var _isNumber = function(a){ return Number.isInteger(a); }
return {
add: add,
subtract: subtract,
multiply: multiply,
divide: divide
}
}())
<body>
<script src="./calculator.js"></script>
<script src="./main.js"></script>
</body>
https://auth0.com/blog/javascript-module-systems-showdown/
https://www.sitepoint.com/understanding-requirejs-for-effective-javascript-module-loading/
PROS
Simple: a developer can grasp the concept without looking at the docs.
Dependency management is integrated: modules require other modules and get loaded in the needed order.
require can be called anywhere: modules can be loaded programmatically.
Circular dependencies are supported.
CONS
Synchronous API makes it not suitable for certain uses (client-side).
One file per module.
Browsers require a loader library or transpiling.
No constructor function for modules (Node supports this though).
Hard to analyze for static code analyzers.
module.exports = {
add : function (a, b) { return a + b; },
subtract : function (a, b) { return a - b; },
multiply : function (a, b) { return a * b; },
divide : function (a, b) { return a / b; }
}
exports.add = function (a, b) { return a + b; }
exports.subtract = function (a, b) { return a - b; }
exports.multiply= function (a, b) { return a * b; }
exports.divide = function (a, b) { return a / b; }
var _isNumber = function(a){ return Number.isInteger(a); }
var calculator = require('./calculator.js');
console.info(calculator.add(1, 3));
https://auth0.com/blog/javascript-module-systems-showdown/
https://www.sitepoint.com/understanding-requirejs-for-effective-javascript-module-loading/
PROS
Asynchronous loading (better startup times).
Circular dependencies are supported.
Compatibility for require and exports.
Dependency management fully integrated.
Modules can be split in multiple files if necessary.
Constructor functions are supported.
Plugin support (custom loading steps).
CONS
Slightly more complex syntactically.
Loader libraries are required unless transpiled.
Hard to analyze for static code analyzers.
define(function () {
var add = function (a, b) { return a + b; }
var subtract = function (a, b) { return a - b; }
var multiply= function (a, b) { return a * b; }
var divide = function (a, b) { return a / b; }
return {
add: add,
subtract: subtract,
multiply: multiply,
divide: divide
}
});
requirejs(['./calculator'], function (calculator) {
console.info(calculator.add(1, 3));
});
http://2ality.com/2014/09/es6-modules-final.html
https://auth0.com/blog/javascript-module-systems-showdo
export default function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }
export function multiply(a, b) { return a * b; }
export function divide(a, b) { return a / b; }
import add, {subtract, multiply, divide} from './calculator';
import { default as add, subtract, multiply, divide} from './calculator';
wn/
Hoisting -> https://www.w3schools.com/js/js_hoisting.asp
Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).
https://blog.mariusschulz.com/2016/01/06/function-definitions-in-javascript
Function Declaration
Function Expression
Read from page no. 25 to page no. 29 - The Principles of object-oriented javascript - by Nicholas C. Zakas
Read from page no. 25 to page no. 29 - The Principles of object-oriented javascript - by Nicholas C. Zakas
function sayNameForAll(label) {
console.log(label + " : " + this.name);
}
var tyson = { name: "Tyson" };
var hawking = { name: "Hawking" };
sayNameForAll.call(tyson, 'Family Name(Call)');
sayNameForAll.call(hawking, 'My Family Name(Call)');
sayNameForAll.apply(tyson, ['Family Name(Apply)']);
sayNameForAll.apply(hawking, ['My Family Name(Apply)']);
var callTyson = sayNameForAll.bind(tyson);
var callHawking = sayNameForAll.bind(hawking);
callTyson('Family Name(Bind)');
callHawking('My Family Name(Bind)');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
var cosmologist = { name: "Hawking" }
var books = { no: 7, famousOne: "A Brief History of Time"}
var brief = `${books.famousOne}
is a popular-science book on cosmology by ${cosmologist.name}`;
var message = books.famousOne + "\n" +
"is a popular-science book on cosmology by " + cosmologist.name;
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
const cosmologist = {
firstName: 'stephen',
lastName: 'Hawking'
}
const { firstName, lastName } = cosmologist;
console.info(firstName);
console.info(lastName);
var books = ['A Brief History of Time', 'The Universe in a Nutshell', 'On the Shoulders of Giants'];
const [famousOne, ...restBooks] = books;
console.info(famousOne);
console.info(restBooks);
https://medium.com/ecmascript-2015/default-rest-spread-f3ab0d2e0a5e
function add(a, b) {
return a + (b || 0);
}
function add(a, b = 0) {
return a + b;
}
https://medium.com/ecmascript-2015/default-rest-spread-f3ab0d2e0a5e
https://codingwithspike.wordpress.com/2016/06/11/javascript-rest-spread-operators/
function add() {
var result = 0;
for (var i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
function sum(...numbers) {
var result = 0;
numbers.forEach(function (number) {
result += number;
});
return result;
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://codingwithspike.wordpress.com/2016/06/11/javascript-rest-spread-operators/
Different
Spread
When using spread, you are expanding a single variable into more:
Rest
When using rest arguments, you are collapsing all remaining arguments of a function into one array:
https://stackoverflow.com/questions/33898512/spread-operator-vs-rest-parameter-in-es2015-es6?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
React is trying to solve this problem by using something called virtual DOM; a DOM kept in memory. Any view changes are first reflected to virtual DOM, then an efficient diff algorithm compares the previous and current states of the virtual DOM and calculates the best way (minimum amount of updates needed) to apply these changes. Finally those updates are applied to the DOM to ensure minimum read/write time. This is the main reason behind React’s high performance
Wrtie application using react.createEllemet at html page after reference react and react dom scripts
Introduce JSX file
First Component print string
how to bind
Embedding Expression
React.createElement(name, props, children)
Show an example about React.createElement
Introduce JSX file
First Component print string
how to bind
Embedding Expression
A demo to show how setState works
Change text (onChange) example, check after change directly (setState Async)
Composing Components
Extracting Components
static defaultProps
import PropTypes from 'prop-types';
MyComponent.propTypes = { children: PropTypes.element.isRequired };
User Card
Shared text boxes
One parent to components
And introduce component at separates files
Shared text boxes
One parent to components
Celsius & fahrenheit
Think how to manage this problem using you mind
Meaning of reducer?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
They are used to reduce a collection of values down to a single value.
https://redux.js.org/basics/actions
https://redux.js.org/basics/reducers
https://redux.js.org/basics/reducers
https://redux.js.org/basics/store
Full React+Redux Demo
Middleware Demo
Full React+Redux Demo
Middleware Demo
https://jsonplaceholder.typicode.com/
Demo for ajax call
Get list and render it.