0% found this document useful (0 votes)
14 views

Introduction To React - Js and Redux

The document introduces React.js and Redux. It discusses what front-end frameworks are and why additional tools are needed beyond just JavaScript. React.js is presented as a popular front-end framework that uses a virtual DOM for efficient UI updates. The Flux architecture and unidirectional data flow are described as an improvement over traditional MVC patterns. React.js implements the view layer of MVC using reusable UI components and a virtual DOM to optimize DOM updates.

Uploaded by

Ion Bogdan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Introduction To React - Js and Redux

The document introduces React.js and Redux. It discusses what front-end frameworks are and why additional tools are needed beyond just JavaScript. React.js is presented as a popular front-end framework that uses a virtual DOM for efficient UI updates. The Flux architecture and unidirectional data flow are described as an improvement over traditional MVC patterns. React.js implements the view layer of MVC using reusable UI components and a virtual DOM to optimize DOM updates.

Uploaded by

Ion Bogdan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Introduction to

React.js(and Redux!)

1
React.js

What is a Front-End
Framework ?

2
React.js WEB Browser Beach

Javascript FRONT END


Framework

USER

AJAX
HTTP

WEB Server Ocean HTTP

HTTP HTTP

Web Dynamic
Server Web Dynamic

Web Service BACK END


Server

Dabase requests

DATA 3
React.js

Front End
 Everything running on the web browser !!
 Basic languages
▪ HTML
▪ CSS
▪ JAVASCRIPT
 Lots of toolboxes !!
▪ Jquery
▪ AJAX
▪ Canvas
▪ WebGL
▪ …
4
React.js

Why do we need additional


tools ?
 Everything can be done through pure JAVASCRIPT !
 right but hard!
 Front End Framework
▪ Help to organize front end development
▪ Provide lots of predefined components
▪ Allow the creation of components
▪ Help to gain time !!
(depending on your front end framework knowledge !)

5
React.js

What is the best Frond End


Framework ?
 It depends of what you want!
▪ Time to learn
▪ Front End efficiency
▪ Modularity
▪ Component creation complexity
▪ Community Size
▪ Maturity

6
What is a front end FrameWork ?

Frond-End Solutions Comparison

https://www.valuecoders.com/blog/wp-
content/uploads/2016/11/Angular-react-and-vue-comparision.png
What is a front end FrameWork ?

Frond-End Solutions Comparison

http://stefankrause.net/js-frameworks-benchmark4/webdriver-ts/table.html
What is a front end FrameWork ?

Frond-End Solutions Comparison

http://stateofjs.com/2016/frontend/
What is a front end FrameWork ?

Frond-End Solutions Comparison

https://wptavern.com/state-of-javascript-survey-results-published-react-emerges-as-
clear-winner-in-front-end-frameworks
What is a front end FrameWork ?

Frond-End Solutions Comparison


React.js

Flux and react.js


Concepts

12
Flux and React.js Concepts

Why current approaches


are not sufficient ?

https://www.youtube.com/watch?v=Bic_sFiaNDI
13
Flux and React.js Concepts

Current State: MVC

https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html

14
Flux and React.js Concepts

Current State: MVC


Model Model  Model B needs (depends on) model A
A B
 Model A needs to be updated first
and then model B
Model Model  Idem if Model C and Model D needs model A
C D

Model Model  Model B may needs also on model C


A B
 Model A needs to be updated first,
then model C and finally Model B
Model Model  Update needs to be propagated and we need
C D
to manage that
15
Flux and React.js Concepts

Current State: MVC


What happen when we scale up ?

Model Model Model Model Model Model Model

Model Model Model Model Model Model Model

Model Model Model Model Model Model Model

Model Model Model Model Model Model Model

16
Flux and React.js Concepts

Current State: MVC


What happen when we scale up ?

17
Flux and React.js Concepts

Current State: MVVM (Model View ViewModel)


 Angular.js data binding

 No more controller for managing model update events instead

18
Flux and React.js Concepts

Current State: MVVM (Model View ViewModel)


 Angular.js data binding

 More details information below


https://docs.angularjs.org/guide/scope#integration-with-the-browser-event-loop

19
Flux and React.js Concepts

Proposition: Flux
 Single direction data flow: FLUX

https://facebook.github.io/flux/docs/in-depth-overview.html#content

20
Flux and React.js Concepts

Proposition: Flux
 Details information and explanation here

https://facebook.github.io/flux/docs/in-depth-overview.html#content

21
Flux and React.js Concepts

UI update Issue
 How updating web page efficiency after data modification ?

{ text: 'message 1'} <li>


{ text: 'message 2'} <div>message 1</div>
<div>message 2</div>
<li>
+
Append
{ text: 'message 3'}
 <div>message 2</div>

22
Flux and React.js Concepts

UI update Issue
 How updating web page efficiency after data modifications ?

<li>
{ text: 'message 1'} <div>message 1</div>
{ text: 'message 2'} <div>message 2</div>
{ text: 'message 3'} <div>message 3</div>
<li>

 We want to always re-render!

23
Flux and React.js Concepts

Proposition: React.js
 What is React.js?
 A library for building reusable UI components
 Implements one-way reactive data flow
 Mostly use as the V of the MVC.

 React.js Properties
 Use the Javascript syntax extension (JSX)
 Optimize the DOM Update through Virutal DOM

24
Flux and React.js Concepts

React.js : Virtual DOM


Initial States
▪ Light copy of the DOM
Virtual DOM ▪ Quick navigation and update
▪ Detached from Browser specific

▪ Hierarchical component view


DOM ▪ Could update and navigate slowly
▪ Browser specific

Web Page

Ref: http://reactkungfu.com/2015/10/the-difference-between-virtual-dom-and-dom/
25
Flux and React.js Concepts

React.js : Virtual DOM

Virtual DOM

DOM

Web Page

Initial State of DOM A state changes on A diff is computed The DOM and
and Virtual DOM the Virtual DOM between old web page are re-
Virtual Dom and render according
new Virtual DOM the computed diff

26
Flux and React.js Concepts

React.js objects
 ReactElement
▪ Lowest type of virtual dom
 ReactNode
▪ Hierachical Element of the virtual dom
▪ ReactElement, string, number
▪ Array of virtual nodes
 ReactComponent Virtual DOM

▪ Specification of how to build react


DOM
elements
Web Page

27
Flux and React.js Concepts

React.js Component
 In react.js everything (mostly) is a component
UI events for the current component

COMPONENT
Init Data
(props)
onValidate
Data
onClick (state)

onDataReceived
RENDER
VIRTUAL DOM
(for the current
component)
SPECIFICATION

28
Flux and React.js Concepts

React.js Component
import React, { Component } from 'react'; App.js
import React from 'react'; Index.js class App extends Component {
import ReactDOM from 'react-dom'; constructor(props) {
import App from './App'; super(props);
this.state = { title:this.props.title, };
ReactDOM.render(<App />, this.handleChangeTitle=this.handleChangeTitle.bind(this);
document.getElementById('root')); }

handleChangeTitle(e){
this.setState({title:e.target.value});
}

render() {
return (
<div className="App">
<h1> this is my first React Component</h1>
<label htmlFor="titleInput">Title </label>
<input type="text" id="titleInput"
onChange={this.handleChangeTitle}
value={this.state.title}
/>
<h3>{this.state.title}</h3>
</div>
); }}
export default App; 30
Flux and React.js Concepts

React.js Component
import React, { Component } from 'react'; App.js
class App extends Component {
constructor(props) {
super(props);
this.state = { title:this.props.title, };
this.handleChangeTitle=this.handleChangeTitle.bind(this); UI events for the current component
}
COMPONENT
Init Data
handleChangeTitle(e){ (props)
onValidate
this.setState({title:e.target.value}); Data
} onClick (state)

render() { onDataReceived
RENDER
VIRTUAL DOM
return ( (for the current
component)
<div className="App"> SPECIFICATION
<h1> this is my first React Component</h1>
<label htmlFor="titleInput">Title </label>
<input type="text" id="titleInput"
onChange={this.handleChangeTitle}
value={this.state.title}
/>
<h3>{this.state.title}</h3>
</div>
); }}
export default App; 31
Flux and React.js Concepts

React.js From JSX to JS


var profile = <div>
<img src="avatar.png" className="profile" />
<h3>{[user.firstName, user.lastName].join(' ')}</h3>
</div>;

RENDER

var profile = React.createElement("div", null,


React.createElement("img", { src: "avatar.png", className: "profile" }),
React.createElement("h3", null, [user.firstName, user.lastName].join(" "))
);

More information herehttps://jasonformat.com/wtf-is-jsx/ 32


Flux and React.js Concepts

React.js Component
Application DOM
<html lang="en">
<head>
<meta charset="utf-8">
<title>React App</title>
</head>
<body style="">
<div id="root">
<div data-reactroot="" class="App">
<h1> this is my first React Component</h1>
<label for="titleInput">Title </label>
<input type="text" class="form-control" id="titleInput">
<h3></h3>
</div>
</div>
</body>
</html>

33
Flux and React.js Concepts

Syntax
 Javascript based on the ES6 standard
 Object syntactic sugar
 New symbols usage (generator, arrow, functions)
 Set of libraries (promises, new collections, types arrays)

34
Flux and React.js Concepts

Syntax ES6
From http://slidedeck.io/DonaldWhyte/isomorphic-react-workshop
CLASSES INHERITENCE
class Point { class ColorPoint extends Point {
constructor(x, y) { constructor(x, y, color) {
this.x = x; this.y = y; super(x, y);
} this.color = color;
toString() { return `(${this.x}, ${this.y})`; } }
} toString() { return super.toString() + ' in ' + this.color; }
}
IMPORTING OTHER MODULES
Modules are JavaScript files. EXPORTING SYMBOLS
// import foo.js in same dir as current file import foo foo.js:
from './foo'; export function foobar(num) { console.log('FOOBAR:', num); }
foo.foobar(42);
EXPORTING ENTIRE OBJECTS
// import specific variables/functions from a module person.js:
import { foobar } from './foo'; foobar(42); export default { name: 'Donald', age: 24 };
another_file.js
LET and CONST import person as './person'; console.log(person.name);
const x_const // outputs 'Donald'
Let x_var
FUNCTION
x_var = x_var +1 ()=>{return ‘hello’;}
x_const = x_const +50 //  error

35
Flux and React.js Concepts

React ToolBoxe : Configure a read.js project

https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr
36
React.js

React.js : Let’s go!

37
Let’s go!

Installation
https://facebook.github.io/react/docs/installation.html

 Nodes.js
 Npm

npm install -g create-react-app


create-react-app my-app
cd my-app
npm start

npm run build

38
Let’s go!

It is your turn !
 Create App allowing to get as input a
title and print it below
 Your App component must be
initialized with the title property =
‘default_title ’

39
Let’s go!

It is your turn !
 Update the number of mouse over the
printed title

40
Let’s go!

Best practices
 Divide your application into components

41
Let’s go!

Best practices
 Divide your application into components

42
Let’s go!

Best practices
 Displaying (presentational Component) Vs Processing (container Component)

VS

43
Let’s go!

Best practices
 Displaying Vs Processing

44
Let’s go!

Best practices
 Displaying Vs Processing

Process Data

Robot Part
Display Data
Label Properties Visual

45
Let’s go!

It is your turn !
 Create the following application
 Create
▪ A main component initialized with
a json file
▪ A Left side component
▪ A Robot component
▪ A Label component for the Robot
Component

All steps available at:


https://github.com/jacques-saraydaryan/front-end-react.js.git
46
Let’s go!

It is your turn !
Main

LeftSide
Robot

Label

Visual

47
Let’s go!

It is your turn !
 Same as previously but with a list of
robots
 Some robot can have a visual as a video

48
Let’s go!

It is your turn !
 Add a Part Component using
 Description Component
 Price Component
 Visual Component
 Add a MiddleSide Component
displaying the list of parts of the
selected robot

49
Let’s go!

It is your turn !
Main
LeftSide MiddleSide
Robot
Label

Visual
Part
Description
Price

50
Let’s go!

It is your turn !
Robots_parts.json

{"robots":[ "parts":[
{ {
"id":1, "id":"A1",
"title":"robotA", "title":"WheelA",
"visual_type":"img", "price":10
"visual_src":"https://www.robot-advance.com/EN/ori-wowwee- },
mip-white-robot-1281_1613.jpg", {
"parts":["A1","A1","A1","A1","A4"] "id":"A2",
}, "title":"WheelB",
{ "price":15
"id":2, },
"title":"robotB", {
"visual_type":"video", "id":"A3",
"visual_src":"https://www.youtube.com/embed/ePINYZK4p5Y", "title":"WheelC",
"parts":["A2","A2","A4"] "price":150
}, },
], {
"id":"A4",
"title":"Contrôleur de Servomoteurs USB SSC-32U Lynxmotion",
"price":57
}]
}

Npm install json-loader


51
Let’s go!

It is your turn !
 Add a RightSide Component using
 Panel Component displaying
selected part

52
Let’s go!

It is your turn !
Main
LeftSide MiddleSide RightSide
Robot Panel
Label
Visual
Part
Description
Price

Visual

Price

53
React.js

React.js :
Our current State
Redux as enhancement

54
Redux

React.js and so?


 Pro
 Components Based
 Extremely efficient (Virtual Dom)
 Easy to write module base code
 UI Test Cases easy to write
 Con
 Only for the view layer
 Write visual component into Javascript
 Hard to learn
 Hierarchical dependencies !

55
Redux

Redux

Can be view as an
implementation of Flux

56
Redux

Redux

https://www.slideshare.net/JonasOhlsson/using-redux

57
Redux

Redux
STORE
OLD STATE

NEW STATE
COMPONENT
ACTION

ACTION REDUCER A
COMPONENT
SUBSCRIBERS

COMPONENT
REDUCER B

58
Redux

Redux export const myAction =


ACTION () => {
return { type: ‘A', value: 2 };
1 Define actions }

function app(state = 0, action) {


OLD STATE
switch (action.type) {
case ‘A': return state + action.value
NEW STATE
case ‘B': return 0
ACTION default: return state
2 Define a Reducer }
REDUCER A }

STORE
import { createStore } from 'redux';
3 Create A Store OLD STATE

const store = createStore(app);


with the Reducer ACTION

REDUCER A

4 Component register
STORE
to the Store
OLD STATE

store.subscribe(() => console.log(store.getState()) )


ACTION

REDUCER A
SUBSCRIBERS

59
Redux

Redux in practice (1/4)


 Install reduce components
npm install redux

npm install react-redux

 Create actions and reducers into dedicated files and


directories

 Use Global reducers merging several reducers


index.js robotReducer.js

import { combineReducers } from 'redux'; const robotReducer= (state={},action) => {


import robotReducer from './robotReducer'; console.log(action);
switch (action.type) {
import partReducer from './partReducer';
case 'UPDATE_SELECTED_ROBOT':
return action.obj;
const globalReducer = combineReducers({
default:
robotReducer: robotReducer, return state;
partReducer: partReducer }
}); }

export default globalReducer; export default robotReducer; 60


Redux

Redux in practice (1/4)


 Install reduce components http://redux.js.org/docs/Troubleshooting.html

npm install redux

npm install react-redux

 Create actions and reduces into dedicated files and


directory

 Use Global reducers merging several reducers


index.js robotReducer.js

import { combineReducers } from 'redux'; const robotReducer= (state={},action) => {


import robotReducer from './robotReducer'; console.log(action);
switch (action.type) {
import partReducer from './partReducer';
case 'UPDATE_SELECTED_ROBOT':
return action.obj;
const globalReducer = combineReducers({
default:
robotReducer: robotReducer, return state;
partReducer: partReducer }
}); }

export default globalReducer; export default robotReducer; 61


Redux

Redux in practice (2/4)


 Use react-redux tools
 Provider to deliver service to all components
import { Provider } from 'react-redux';

render() {
return (
<Provider store={store} >
<div className="container-fluid">
<div className="row">
<h1> Welcome to robot shop</h1>
</div>
<div className="row">
<div className="col-md-4 col-lg-4" >
<LeftSide
robots={this.state.robot_list}
/>

</div>
</div>
</div>
</Provider>
);
}

62
Redux

Redux in practice (3/4)


 Use react-redux tools
 Connect to dispatch action, and subscribe to modifications
dispatch action
//load the connect tool
import { connect } from 'react-redux';
//load the custom action
import {setSelectedRobot} from '../../actions';

class Robot extends Component {


...
handleOnRobotSelected(robot_obj){
//get the store contained into props and
// 'sent' an action
this.props.dispatch(setSelectedRobot(robot_obj));
}
...
//link the Robot Component to the store provided by the Provider Tool
//No need to subscribe that's why there is no first parameter to the
// connect function connect()(Robot)
export default connect()(Robot);

63
Redux

Redux in practice (4/4)


 Use react-redux tools
 Connect to dispatch action, and subscribe to modifications
subscribe to modifications
//load the connect tool
import { connect } from 'react-redux';
class MiddleSide extends Component {
...
//render function use to update the virtual dom
render() {
return (
<div>
<Part
part={this.props.parts[0]}
/>
</div>
); } }
const mapStateToProps = (state, ownProps) => {
return {
parts: state.robotReducer.parts
} };

//connect the MiddleSide component to the store provided by the Provider Tool
// Specify a function (mapStateToProps) allowing to trig on store state modification
// when a store state is modify the mapStateToProps is launched and associate the
state.robotReducer.parts value to the local propery parts (this.props.parts)
export default connect(mapStateToProps)(MiddleSide);

64
Redux

It is your turn !
 Create 2 Actions modifying the selected
Robot obj and the selected Part obj

 Create 1 reducer ‘robotReducer’ in


charge of processing the selected Robot obj

 Create 1 reduce ‘partReducer’ in charge


of processing the selected Part obj

65
Redux

It is your turn !
 Modifying the previous project so as to
▪ Dispatch selected robot in the Robot
component
▪ Subscribe to store and update list of
parts in the MiddleSide component
Main

▪ Dispatch selected part in the Part


LeftSide MiddleSide RightSide

Robot Panel
Label

Part
Visual

Description

component Price

Visual

▪ Subscribe to store and update Part in


the RightSide component Price

66
Réferences
References

References

68
References
Réferences

References

▪ React.js and Flux


http://soat.developpez.com/tutoriels/javascript/architecture-flux-avec-react/
https://www.tutorialspoint.com/reactjs/reactjs_using_flux.htm
https://medium.com/@jetupper/hello-react-js-b87c63526e3a
DEVOX France: https://www.youtube.com/watch?v=IFM8krjbKmQ

▪ React.js and Redux


http://www.troispointzero.fr/2016/03/reactjs-redux-pour-des-lendemains-qui-chantent-
premiere-partie/
https://www.codementor.io/mz026/getting-started-with-react-redux-an-intro-8r6kurcxf
http://www.sohamkamani.com/blog/2017/03/31/react-redux-connect-explained/

▪ Tutorials
https://github.com/HurricaneJames/dex/blob/master/doc/Building%20Components%20
with%20React.js%20and%20Flux.md
https://github.com/react-bootcamp/react-workshop

▪ Course tutorial
https://github.com/jacques-saraydaryan/front-end-react.js
69
Jacques Saraydaryan
Jacques.saraydaryan@cpe.fr

You might also like