SlideShare a Scribd company logo
1 of 27
Download to read offline
Front End Workshops
ReactJS - Part I
Raúl Delgado & Marc Torrent
rdelgado@visual-engin.com
mtorrent@visual-engin.com
React what??
Functional Reactive Programming (FRP)
1. Functions at the heart of code
2. Data mutation is Bad (should be avoided)
1. Composability → The system is seen as a composition
of functions
2. Purity → functions which are free of side-effects and
don't mutate their own arguments
3. Higher Order functions → Have a function as an
argument and/or return another function
4. Immutability → functions always return a new object /
array or function derived from the arguments, but the
arguments remain the same
PREDICTABILITY
FRP - Examples
function sumArray(values) {
return values
.map(Number)
.reduce((total, value) => total + value);
}
sumArray([1, '2', '30']); // 33
function push(array, element) {
// Add new element to array
array.push(element);
return element;
}
function concat(array, elements) {
// Create new array with all values
return array.concat(elements);
}
let arr = [1, 2, 3];
let addMore = true;
// Adding elements:
arr.push(4, 5);
if (addMore) {
arr.push(6, 7);
}
// Or the functional way
arr = arr
.concat([4, 5])
.concat(addMore ? [6, 7] : []);
ReactJS and FRP
ReactJS fits the FRP Paradigm:
1. UI is predictable → ReactDOM.render();
2. UI is composable →
<ParentComonent><ChildComponent /></ParentComponent>
3. Higher-order components give us more code reusability and increase
composability.
a. A component taking a component as an argument and wrapping
aditional content around it to provide some context. This would be
the case of a modal component.
b. A component returning another component (i.e. a factory). This
would be the case if you want to reuse the functionality of a base
component into a new component.
And what about Purity and Immutability? … AMEN !
Reactivity: One Way Binding
<ComponentA /> {this.props}
<ComponentB /> {this.props}
<ComponentC /> {this.props}
Update in parent props →
updates children props
<ComponentA /> {this.state} <ComponentB /> {this.props}
Update in parent state → updates children props
THE PROBLEM:
When we re-render a component, it will always return a new instance of
a DOM element. The old element would then be removed from the tree
and the new one would be added. With no existing mechanisms for the
DOM to know if those two elements are related, we would have to re-
render it completely.
THE SOLUTION:
A component is a function creating virtual DOM elements instead of real
DOM elements. When a re-rendering occurs, the virtual DOM runs a diff
algorithm to create a set of changes to apply to the real DOM (a patch)
Virtual DOM
1. An application has a state
2. This state is rendered in a tree of
components, using a Virtual DOM.
Data is flowing down the tree.
3. The rendered UI will generate
events from user interactions
which will update the application
state.
4. Following the state update, the UI
will be updated
5. The application state can also
receive updates from the server
Application Flow: The Flux Pattern
Server Side Rendering
BackEnd Rest API
Façade -
Middleware Server
Routing: React-Router
HTTP 200: React.
renderToString
HTML with full react
components rendered
Client: React &
React-Router
9flats - Airbnb - Alipay - Atlassian - BBC - Box - Capital
One - Coursera -Dailymotion - Deezer - Docker -
Expedia - Facebook - Fotocasa - HappyFresh - IMDb -
Instacart - Instagram - Khan Academy - Klarna - Lyft -
NBC - Netflix - NFL - Paypal - Periscope - Ralph Lauren -
Reddit - Salesforce - Stack Overflow - Tesla - Tmall -
The New York Times - Twitter Fabric - Twitter Mobile -
Uber - WhatsApp - Wired - Yahoo - Zendesk
Who is using ReactJS?
Technology Stack
JSX
JSX is a JavaScript syntax extension that looks similar to XML. You can
use a simple JSX syntactic transform with React.
JSX is optional, however it is recommended because it is a concise and
familiar syntax for defining tree structures with attributes.
JSX
<div> texto </div>
<div className=”rojo”> texto </div>
<Menu className=”navbar” />
<UsersTable>
<User name=”Tyrion” />
</UsersTable>
The react-dom is a package provides DOM-specific methods that can be used at
the top level of your app and as an escape hatch to get outside of the React
model if you need to.
Method render: Render a ReactElement into the DOM in the supplied container
and return a reference to the component.
React-DOM
import ReactDOM from 'react-dom';
ReactDOM.render(
<App families={[“Stark”, “Lannister”, “Targaryen”,
“Baratheon” ]} />,
document.querySelector('.container'),
() => { console.log("I'm a callback, you know nothing");
);
Events & Callbacks
class Lannister extends React.Component{
constructor(props) {
super(props);
this.state = { motto: "Hear me roar" };
this.update = this.update.bind(this);
}
update() { this.setState( { motto: "A lannister always pays his debts" } ) }
render() {
return (
<div>
<h3>Lannister</h3>
name: {this.props.name} <br/>
motto: {this.state.motto} <br/>
<ButtonChange update={this.update} />
</div>
);
}
}
const ButtonChange = ({update}) => {
return ( <button onClick={update} > change </button> )
}
ReactDOM.render( <Lannister name="Tyrion" />, document.getElementById('container') );
Component State
Props:
are a Component's configuration, its options.
They are received from above and immutable
as far as the Component receiving them is
concerned.
A Component cannot change its props, but it is
responsible for putting together the props of its
child Components.
Only Props ? functional components
Props vs State
State:
The state starts with a default value when a
Component mounts and then suffers from
mutations in time (mostly generated from user
events).
A Component manages its own state internally,
but—besides setting an initial state—has no
business fiddling with the state of its children.
You could say the state is private.
If you need to use state or function hooks,
you need class based component
Props:
are a Component's configuration, its options.
They are received from above and immutable
as far as the Component receiving them is
concerned.
A Component cannot change its props, but it is
responsible for putting together the props of its
child Components.
Only Props ? functional components
Props vs State
State:
The state starts with a default value when a
Component mounts and then suffers from
mutations in time (mostly generated from user
events).
A Component manages its own state internally,
but—besides setting an initial state—has no
business fiddling with the state of its children.
You could say the state is private.
If you need to use state or function hooks,
you need class based component
- props state
Can get initial value from parent
Component?
Yes Yes
Can be changed by parent Component? Yes No
Can set default values inside Component?* Yes Yes
Can change inside Component? No Yes
Can set initial value for child Components? Yes Yes
Can change in child Components? Yes No
Form components such as <input>, <textarea>, and <option> differ from other
native components because they can be mutated via user interactions.
A controlled <input> has a value prop. Rendering a controlled <input> will
reflect the value of the value prop.
A controlled <input> has a value
prop. Rendering a controlled
<input> will reflect the value of the
value prop.
User input will have no effect on
the rendered element because
React has declared the value to be
Fire and Blood.
To update the value in response to
user input, you could use the
onChange event
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<input type="text" value={this.state.value}
onChange={this.handleChange}
defaultValue=”Fire and Blood”
/>
);
Controlled components
Components LifeCycle
Hook Name
Lifecycle
Phase
setState Client Server
componentWillMount Mounting ✔ ✔ ✔
componentDidMount Mounting ✔
componentWillReceiveProps Updating ✔ ✔ ✔
shouldComponentUpdate Updating ✔ ✔
componentWillUpdate Updating ✔ ✔
componentDidUpdate Updating ✔
componentWillUnmount Unmounting ✔
Enough Theory!
Let’s get practical!
https://github.com/rdavisual/react-project-base/tree/reactjs-game-3x3 esta rama esta creada desde el
punto donde se dejo el workshop.
El componente simplebox recibirá un nueva propiedad que será available(boolen). Dependiendo de
este parámetro el componente simplebox llamará a la función que se le pasa (clickHandle).
En el componente table añadir un nuevo atributo al state que sea “available” : true, pasar este nuevo
atributo a las simplebox como propiedad (en el render).
En la función de click de table cambiar el atributo del state available a false y comprobar que no se
vuelve a llamar al clicar cualquier celda.
resultado: solo se puede hacer un click a la table.
Ejercicio 1
Ejercicio 2
En el componente table modificar el state, en la parte del constructor, crear un único atributo que se
llamara table. Este tendrá un array de objetos que contendrán las propiedades de las “celdas” de
nuestra tabla. Cada objeto tendrá la siguiente estructura y valores iniciales:
{ id:<identificador único> , classBox: "", available: true};
En el momento de crear cada simplebox (en la función render), recogeremos del state los tributos
de cada celda y se los pasaremos a la simplebox. “Una simplebox - un objeto celda”a
Modificar la función clickHandler del componente table para que cambie el atributo classBox de la
celda que se ha asignado a la simpleBox. Recordar que el state no se actualiza, sino que se tiene
que reescribir entero (setState).
resultado: se cambia el color de la celda clicada.
Ejercicio 3
Creación de un nuevo componente: game
Este componente tendrá en el state 2 objetos de tipo jugador y un turn(turno del jugador) de tipo
string. El objeto jugador tendrá la siguiente estructura:
{ id:<identificador único> , nombre: "nombre jugador", classPlayer: “black”};
la classPlayer debe ser la clase que cambia de color la box ( black, red o alguna propia creada )
Este componente será el que renderice el componente de table.
resultado: enseña la misma tabla
Ejercicio 4
El componente table recibirá 2 nuevas propiedades: una función y la clase del color que se
querrá pintar. La clase dependerá del turno del jugador.
La función cambiará el turno del jugador.
En el componente table, en la función clickHandle se cambiará al color que se le haya pasado
por propiedades y al final de esta función se llamará a la función también pasada por
propiedades.
Finalmente en el render del componente game, aparte de mostrar la table mostrará el nombre
del jugador al que “le toca”.
resultado: clicks de diferentes colores
Ejercicio 5
Construye la lógica del juego del 3 en raya en el componente game.
Una pista de la función para saber el ganador:
panel = [0,0,0,0,0,0,0,0,0]
hasWin(playerId) {
// -
let bool=(panel[0] == playerId && panel[1] == playerId && panel[2]==playerId);
bool=bool || (panel[3] == playerId && panel[4] == playerId && panel[5]==playerId);
bool=bool || (panel[6] == playerId && panel[7] == playerId && panel[8]==playerId);
// |
bool=bool || (panel[0] == playerId && panel[3] == playerId && panel[6]==playerId);
bool=bool || (panel[1] == playerId && panel[4] == playerId && panel[7]==playerId);
bool=bool || (panel[2] == playerId && panel[5] == playerId && panel[8]==playerId);
//  /
bool=bool || (panel[0] == playerId && panel[4] == playerId && panel[8]==playerId);
bool=bool || (panel[2] == playerId && panel[4] == playerId && panel[6]==playerId);
return bool;
}
Workshop 19: ReactJS Introduction

More Related Content

What's hot

Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIVisual Engineering
 
Asyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-sagaAsyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-sagaPedro Solá
 
Async JavaScript Unit Testing
Async JavaScript Unit TestingAsync JavaScript Unit Testing
Async JavaScript Unit TestingMihail Gaberov
 
Introduction to React & Redux
Introduction to React & ReduxIntroduction to React & Redux
Introduction to React & ReduxBoris Dinkevich
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideVisual Engineering
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max PetruckMaksym Petruk
 
Redux training
Redux trainingRedux training
Redux trainingdasersoft
 
Switch to React.js from AngularJS developer
Switch to React.js from AngularJS developerSwitch to React.js from AngularJS developer
Switch to React.js from AngularJS developerEugene Zharkov
 
Workshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design PatternsWorkshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design PatternsVisual Engineering
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with ReduxVedran Blaženka
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 DreamLab
 
Creating a WYSIWYG Editor with React
Creating a WYSIWYG Editor with ReactCreating a WYSIWYG Editor with React
Creating a WYSIWYG Editor with Reactpeychevi
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with ReduxFITC
 

What's hot (20)

React & Redux
React & ReduxReact & Redux
React & Redux
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
 
Asyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-sagaAsyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-saga
 
Async JavaScript Unit Testing
Async JavaScript Unit TestingAsync JavaScript Unit Testing
Async JavaScript Unit Testing
 
Introduction to React & Redux
Introduction to React & ReduxIntroduction to React & Redux
Introduction to React & Redux
 
Let's Redux!
Let's Redux!Let's Redux!
Let's Redux!
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max Petruck
 
Redux training
Redux trainingRedux training
Redux training
 
Switch to React.js from AngularJS developer
Switch to React.js from AngularJS developerSwitch to React.js from AngularJS developer
Switch to React.js from AngularJS developer
 
Workshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design PatternsWorkshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design Patterns
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
 
React hooks
React hooksReact hooks
React hooks
 
Creating a WYSIWYG Editor with React
Creating a WYSIWYG Editor with ReactCreating a WYSIWYG Editor with React
Creating a WYSIWYG Editor with React
 
React on es6+
React on es6+React on es6+
React on es6+
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
 
Intro to ReactJS
Intro to ReactJSIntro to ReactJS
Intro to ReactJS
 
Redux vs Alt
Redux vs AltRedux vs Alt
Redux vs Alt
 

Similar to Workshop 19: ReactJS Introduction

[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksKaty Slemon
 
React State vs Props Introduction & Differences.pptx
React State vs Props Introduction & Differences.pptxReact State vs Props Introduction & Differences.pptx
React State vs Props Introduction & Differences.pptxBOSC Tech Labs
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxBOSC Tech Labs
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfStephieJohn
 
React and Flux life cycle with JSX, React Router and Jest Unit Testing
React and  Flux life cycle with JSX, React Router and Jest Unit TestingReact and  Flux life cycle with JSX, React Router and Jest Unit Testing
React and Flux life cycle with JSX, React Router and Jest Unit TestingEswara Kumar Palakollu
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥Remo Jansen
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
How can you force react components to rerender without calling the set state ppt
How can you force react components to rerender without calling the set state pptHow can you force react components to rerender without calling the set state ppt
How can you force react components to rerender without calling the set state pptBOSC Tech Labs
 
How to use UseContext Hook in React.pptx
How to use UseContext Hook in React.pptxHow to use UseContext Hook in React.pptx
How to use UseContext Hook in React.pptxBOSC Tech Labs
 
React 16: new features and beyond
React 16: new features and beyondReact 16: new features and beyond
React 16: new features and beyondArtjoker
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тягаVitebsk Miniq
 

Similar to Workshop 19: ReactJS Introduction (20)

[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooks
 
ReactJS (1)
ReactJS (1)ReactJS (1)
ReactJS (1)
 
React State vs Props Introduction & Differences.pptx
React State vs Props Introduction & Differences.pptxReact State vs Props Introduction & Differences.pptx
React State vs Props Introduction & Differences.pptx
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
 
React and Flux life cycle with JSX, React Router and Jest Unit Testing
React and  Flux life cycle with JSX, React Router and Jest Unit TestingReact and  Flux life cycle with JSX, React Router and Jest Unit Testing
React and Flux life cycle with JSX, React Router and Jest Unit Testing
 
Intro react js
Intro react jsIntro react js
Intro react js
 
React
ReactReact
React
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
React/Redux
React/ReduxReact/Redux
React/Redux
 
Simple React Todo List
Simple React Todo ListSimple React Todo List
Simple React Todo List
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
ReactJs
ReactJsReactJs
ReactJs
 
How can you force react components to rerender without calling the set state ppt
How can you force react components to rerender without calling the set state pptHow can you force react components to rerender without calling the set state ppt
How can you force react components to rerender without calling the set state ppt
 
How to use UseContext Hook in React.pptx
How to use UseContext Hook in React.pptxHow to use UseContext Hook in React.pptx
How to use UseContext Hook in React.pptx
 
React 16: new features and beyond
React 16: new features and beyondReact 16: new features and beyond
React 16: new features and beyond
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
 

More from Visual Engineering

Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSVisual Engineering
 
Workshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operatorsWorkshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operatorsVisual Engineering
 
Workshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensionesWorkshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensionesVisual Engineering
 
Workshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresWorkshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresVisual Engineering
 
Workhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftWorkhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftVisual Engineering
 
Workshop 25: React Native - Components
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - ComponentsVisual Engineering
 
Workshop 24: React Native Introduction
Workshop 24: React Native IntroductionWorkshop 24: React Native Introduction
Workshop 24: React Native IntroductionVisual Engineering
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedVisual Engineering
 
Workshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effectsWorkshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effectsVisual Engineering
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSVisual Engineering
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IVisual Engineering
 
Workshop 11: Trendy web designs & prototyping
Workshop 11: Trendy web designs & prototypingWorkshop 11: Trendy web designs & prototyping
Workshop 11: Trendy web designs & prototypingVisual Engineering
 
Workshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVCWorkshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVCVisual Engineering
 
Workshop 7: Single Page Applications
Workshop 7: Single Page ApplicationsWorkshop 7: Single Page Applications
Workshop 7: Single Page ApplicationsVisual Engineering
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testingVisual Engineering
 

More from Visual Engineering (20)

Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
 
Workshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operatorsWorkshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operators
 
Workshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensionesWorkshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensiones
 
Workshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresWorkshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - Structures
 
Workhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftWorkhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de Swift
 
Workshop 25: React Native - Components
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - Components
 
Workshop 24: React Native Introduction
Workshop 24: React Native IntroductionWorkshop 24: React Native Introduction
Workshop 24: React Native Introduction
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Workshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effectsWorkshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effects
 
Workshop 16: EmberJS Parte I
Workshop 16: EmberJS Parte IWorkshop 16: EmberJS Parte I
Workshop 16: EmberJS Parte I
 
Workshop 15: Ionic framework
Workshop 15: Ionic frameworkWorkshop 15: Ionic framework
Workshop 15: Ionic framework
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJS
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Workshop 11: Trendy web designs & prototyping
Workshop 11: Trendy web designs & prototypingWorkshop 11: Trendy web designs & prototyping
Workshop 11: Trendy web designs & prototyping
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Workshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVCWorkshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVC
 
Workshop 7: Single Page Applications
Workshop 7: Single Page ApplicationsWorkshop 7: Single Page Applications
Workshop 7: Single Page Applications
 
Workshop 6: Designer tools
Workshop 6: Designer toolsWorkshop 6: Designer tools
Workshop 6: Designer tools
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 

Recently uploaded

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 

Recently uploaded (20)

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 

Workshop 19: ReactJS Introduction

  • 1. Front End Workshops ReactJS - Part I Raúl Delgado & Marc Torrent rdelgado@visual-engin.com mtorrent@visual-engin.com
  • 3. Functional Reactive Programming (FRP) 1. Functions at the heart of code 2. Data mutation is Bad (should be avoided) 1. Composability → The system is seen as a composition of functions 2. Purity → functions which are free of side-effects and don't mutate their own arguments 3. Higher Order functions → Have a function as an argument and/or return another function 4. Immutability → functions always return a new object / array or function derived from the arguments, but the arguments remain the same PREDICTABILITY
  • 4. FRP - Examples function sumArray(values) { return values .map(Number) .reduce((total, value) => total + value); } sumArray([1, '2', '30']); // 33 function push(array, element) { // Add new element to array array.push(element); return element; } function concat(array, elements) { // Create new array with all values return array.concat(elements); } let arr = [1, 2, 3]; let addMore = true; // Adding elements: arr.push(4, 5); if (addMore) { arr.push(6, 7); } // Or the functional way arr = arr .concat([4, 5]) .concat(addMore ? [6, 7] : []);
  • 5. ReactJS and FRP ReactJS fits the FRP Paradigm: 1. UI is predictable → ReactDOM.render(); 2. UI is composable → <ParentComonent><ChildComponent /></ParentComponent> 3. Higher-order components give us more code reusability and increase composability. a. A component taking a component as an argument and wrapping aditional content around it to provide some context. This would be the case of a modal component. b. A component returning another component (i.e. a factory). This would be the case if you want to reuse the functionality of a base component into a new component. And what about Purity and Immutability? … AMEN !
  • 6. Reactivity: One Way Binding <ComponentA /> {this.props} <ComponentB /> {this.props} <ComponentC /> {this.props} Update in parent props → updates children props <ComponentA /> {this.state} <ComponentB /> {this.props} Update in parent state → updates children props
  • 7. THE PROBLEM: When we re-render a component, it will always return a new instance of a DOM element. The old element would then be removed from the tree and the new one would be added. With no existing mechanisms for the DOM to know if those two elements are related, we would have to re- render it completely. THE SOLUTION: A component is a function creating virtual DOM elements instead of real DOM elements. When a re-rendering occurs, the virtual DOM runs a diff algorithm to create a set of changes to apply to the real DOM (a patch) Virtual DOM
  • 8. 1. An application has a state 2. This state is rendered in a tree of components, using a Virtual DOM. Data is flowing down the tree. 3. The rendered UI will generate events from user interactions which will update the application state. 4. Following the state update, the UI will be updated 5. The application state can also receive updates from the server Application Flow: The Flux Pattern
  • 9. Server Side Rendering BackEnd Rest API Façade - Middleware Server Routing: React-Router HTTP 200: React. renderToString HTML with full react components rendered Client: React & React-Router
  • 10. 9flats - Airbnb - Alipay - Atlassian - BBC - Box - Capital One - Coursera -Dailymotion - Deezer - Docker - Expedia - Facebook - Fotocasa - HappyFresh - IMDb - Instacart - Instagram - Khan Academy - Klarna - Lyft - NBC - Netflix - NFL - Paypal - Periscope - Ralph Lauren - Reddit - Salesforce - Stack Overflow - Tesla - Tmall - The New York Times - Twitter Fabric - Twitter Mobile - Uber - WhatsApp - Wired - Yahoo - Zendesk Who is using ReactJS?
  • 12. JSX
  • 13. JSX is a JavaScript syntax extension that looks similar to XML. You can use a simple JSX syntactic transform with React. JSX is optional, however it is recommended because it is a concise and familiar syntax for defining tree structures with attributes. JSX <div> texto </div> <div className=”rojo”> texto </div> <Menu className=”navbar” /> <UsersTable> <User name=”Tyrion” /> </UsersTable>
  • 14. The react-dom is a package provides DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside of the React model if you need to. Method render: Render a ReactElement into the DOM in the supplied container and return a reference to the component. React-DOM import ReactDOM from 'react-dom'; ReactDOM.render( <App families={[“Stark”, “Lannister”, “Targaryen”, “Baratheon” ]} />, document.querySelector('.container'), () => { console.log("I'm a callback, you know nothing"); );
  • 15. Events & Callbacks class Lannister extends React.Component{ constructor(props) { super(props); this.state = { motto: "Hear me roar" }; this.update = this.update.bind(this); } update() { this.setState( { motto: "A lannister always pays his debts" } ) } render() { return ( <div> <h3>Lannister</h3> name: {this.props.name} <br/> motto: {this.state.motto} <br/> <ButtonChange update={this.update} /> </div> ); } } const ButtonChange = ({update}) => { return ( <button onClick={update} > change </button> ) } ReactDOM.render( <Lannister name="Tyrion" />, document.getElementById('container') );
  • 17. Props: are a Component's configuration, its options. They are received from above and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Only Props ? functional components Props vs State State: The state starts with a default value when a Component mounts and then suffers from mutations in time (mostly generated from user events). A Component manages its own state internally, but—besides setting an initial state—has no business fiddling with the state of its children. You could say the state is private. If you need to use state or function hooks, you need class based component
  • 18. Props: are a Component's configuration, its options. They are received from above and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Only Props ? functional components Props vs State State: The state starts with a default value when a Component mounts and then suffers from mutations in time (mostly generated from user events). A Component manages its own state internally, but—besides setting an initial state—has no business fiddling with the state of its children. You could say the state is private. If you need to use state or function hooks, you need class based component - props state Can get initial value from parent Component? Yes Yes Can be changed by parent Component? Yes No Can set default values inside Component?* Yes Yes Can change inside Component? No Yes Can set initial value for child Components? Yes Yes Can change in child Components? Yes No
  • 19. Form components such as <input>, <textarea>, and <option> differ from other native components because they can be mutated via user interactions. A controlled <input> has a value prop. Rendering a controlled <input> will reflect the value of the value prop. A controlled <input> has a value prop. Rendering a controlled <input> will reflect the value of the value prop. User input will have no effect on the rendered element because React has declared the value to be Fire and Blood. To update the value in response to user input, you could use the onChange event handleChange: function(event) { this.setState({value: event.target.value}); }, render: function() { return ( <input type="text" value={this.state.value} onChange={this.handleChange} defaultValue=”Fire and Blood” /> ); Controlled components
  • 20. Components LifeCycle Hook Name Lifecycle Phase setState Client Server componentWillMount Mounting ✔ ✔ ✔ componentDidMount Mounting ✔ componentWillReceiveProps Updating ✔ ✔ ✔ shouldComponentUpdate Updating ✔ ✔ componentWillUpdate Updating ✔ ✔ componentDidUpdate Updating ✔ componentWillUnmount Unmounting ✔
  • 22. https://github.com/rdavisual/react-project-base/tree/reactjs-game-3x3 esta rama esta creada desde el punto donde se dejo el workshop. El componente simplebox recibirá un nueva propiedad que será available(boolen). Dependiendo de este parámetro el componente simplebox llamará a la función que se le pasa (clickHandle). En el componente table añadir un nuevo atributo al state que sea “available” : true, pasar este nuevo atributo a las simplebox como propiedad (en el render). En la función de click de table cambiar el atributo del state available a false y comprobar que no se vuelve a llamar al clicar cualquier celda. resultado: solo se puede hacer un click a la table. Ejercicio 1
  • 23. Ejercicio 2 En el componente table modificar el state, en la parte del constructor, crear un único atributo que se llamara table. Este tendrá un array de objetos que contendrán las propiedades de las “celdas” de nuestra tabla. Cada objeto tendrá la siguiente estructura y valores iniciales: { id:<identificador único> , classBox: "", available: true}; En el momento de crear cada simplebox (en la función render), recogeremos del state los tributos de cada celda y se los pasaremos a la simplebox. “Una simplebox - un objeto celda”a Modificar la función clickHandler del componente table para que cambie el atributo classBox de la celda que se ha asignado a la simpleBox. Recordar que el state no se actualiza, sino que se tiene que reescribir entero (setState). resultado: se cambia el color de la celda clicada.
  • 24. Ejercicio 3 Creación de un nuevo componente: game Este componente tendrá en el state 2 objetos de tipo jugador y un turn(turno del jugador) de tipo string. El objeto jugador tendrá la siguiente estructura: { id:<identificador único> , nombre: "nombre jugador", classPlayer: “black”}; la classPlayer debe ser la clase que cambia de color la box ( black, red o alguna propia creada ) Este componente será el que renderice el componente de table. resultado: enseña la misma tabla
  • 25. Ejercicio 4 El componente table recibirá 2 nuevas propiedades: una función y la clase del color que se querrá pintar. La clase dependerá del turno del jugador. La función cambiará el turno del jugador. En el componente table, en la función clickHandle se cambiará al color que se le haya pasado por propiedades y al final de esta función se llamará a la función también pasada por propiedades. Finalmente en el render del componente game, aparte de mostrar la table mostrará el nombre del jugador al que “le toca”. resultado: clicks de diferentes colores
  • 26. Ejercicio 5 Construye la lógica del juego del 3 en raya en el componente game. Una pista de la función para saber el ganador: panel = [0,0,0,0,0,0,0,0,0] hasWin(playerId) { // - let bool=(panel[0] == playerId && panel[1] == playerId && panel[2]==playerId); bool=bool || (panel[3] == playerId && panel[4] == playerId && panel[5]==playerId); bool=bool || (panel[6] == playerId && panel[7] == playerId && panel[8]==playerId); // | bool=bool || (panel[0] == playerId && panel[3] == playerId && panel[6]==playerId); bool=bool || (panel[1] == playerId && panel[4] == playerId && panel[7]==playerId); bool=bool || (panel[2] == playerId && panel[5] == playerId && panel[8]==playerId); // / bool=bool || (panel[0] == playerId && panel[4] == playerId && panel[8]==playerId); bool=bool || (panel[2] == playerId && panel[4] == playerId && panel[6]==playerId); return bool; }