SlideShare una empresa de Scribd logo
1 de 61
React & Redux for noobs
SERGIO GARCÍA SANTOS
FRONT END DEVELOPER
@sgarcias95
segarcia@pasiona.com
IRENE FOZ ALMAGRO
FRONT END DEVELOPER
@ireefoz10
ifoz@pasiona.com
ReactJS
“A JavaScript library for building user interfaces”
COMPONENT-BASED
UI part split into independent and reusable pieces
REUTILIZATION
Re-use most components across platforms
React Native
Build native mobile apps using JS and React
iOS Android
EFFICIENCY
Updating the browser’s displayed DOM efficiently
.root
.header .body
.content.links.logo .welcome
.list .form
VirtualDOM
Updating the browser’s displayed DOM efficiently
.root
.header .body
.content.links.logo .welcome
.list .form
VirtualDOM
Updating the browser’s displayed DOM efficiently
.root
.header .body
.content.links.logo .welcome
.list .form
.welcome
.form
CALCULATES DIFFERENCES
.root
.header .body
.content.links.logo .welcome
.list .form
VirtualDOM
Updating the browser’s displayed DOM efficiently
.root
.header .body
.content.links.logo .welcome
.list .form
.welcome
.form
APPLIES THEM
.form
.welcome
ReactJS
ReactJS
Fundamentals
JSX
FUNDAMENTALS
JSX
Sugar syntax for the React.createElement() function.
<MyButton color="blue" shadowSize={2}>
Click Me
</MyButton>
React.createElement(
MyButton,
{ color: 'blue', shadowSize: 2 },
'Click Me'
)
JSX
Sugar syntax for the React.createElement() function.
React library must always be in scope from your JSX file
import React from 'react';
import { Link as DomLink } from 'react-router-dom';
const Link = ({ to, className, children }) => (
<DomLink to={to || '/'}>{children} </DomLink>,
);
export default Link;
JSX
Sugar syntax for the React.createElement() function.
Your components’ name must be Capitalized
import React from 'react';
import { Link as DomLink } from 'react-router-dom';
// Good
const Link = ({ to, className, children }) => (
<DomLink to={to || '/'}>{children}</DomLink>
);
// Wrong!
const link = ({ to, className, children }) => (
<DomLink to={to || '/'}>{children}</DomLink>
);
JSX
Sugar syntax for the React.createElement() function.
Use camel case for JSX types
import React from 'react';
import { Link as DomLink } from 'react-router-dom';
// Good
const LinkToHome = ({ to, className, children }) => (
<DomLink to={to || '/'}>{children}</DomLink>
);
// Wrong!
const Linktohome = ({ to, className, children }) => (
<DomLink to={to || '/'}>{children}</DomLink>
);
JSX
Sugar syntax for the React.createElement() function.
Not use general expressions as React element type
import React from 'react';
import { Link as DomLink } from 'react-router-dom’;
const links = { tree: Tree, spinner: Spinner };
// Good
const MockImage = ({ type }) => {
const Image = links[type];
return <Image />
};
// Wrong!
const MockImage = ({ type }) => (
<links[type] />
);
JSX
Sugar syntax for the React.createElement() function.
Component’s children
const Example = () => (<div>Hello</div>);
/* Output:
* ------------------------
* Hello
* ------------------------
*/
String Literals Other components Javascript Expressions Functions Boolean, undefined or null
JSX
Sugar syntax for the React.createElement() function.
Component’s children
const CustomComponent = ({ src }) => ('This is the CustomComponent’s
child');
const Example = ({ src }) => (<CustomComponent />);
/* Output:
* ------------------------
* This is the CustomComponent’s child
* ------------------------
*/
String Literals Other components Javascript Expressions Functions Boolean, undefined or null
JSX
Sugar syntax for the React.createElement() function.
Component’s children
const First = () => 'Hello';
// Hello
const _users = ['Pepe', 'Antonio'];
const Second = () => _users.map((user) => (user));
// PepeAntonio
const Third = () => <div>Hello {users[0]}</div>
// Hello Pepe
Other componentsString Literals Javascript Expressions Functions Boolean, undefined or null
JSX
Sugar syntax for the React.createElement() function.
Component’s children
const users = ['Pepe', 'Antonio'];
const getComponentChildren = () => {
return users.map((user) => <div>Hello user: {user}</div>);
}
const Component = () => getComponentChildren();
// Hello user: Pepe
// Hello user: Antonio
String Literals Other components Javascript Expressions Functions Boolean, undefined or null
JSX
Sugar syntax for the React.createElement() function.
Component’s children
const NullComponent = () => null;
//
const BooleanComponent = () => true;
//
const UndefinedComponent = () => undefined;
//
String Literals Other components Javascript Expressions Functions Boolean, undefined or null
Components & Props
FUNDAMENTALS
React Components
UI part split into independent and reusable pieces
JavaScript function ES6 Class
import React from 'react';
const Title = (props) => (
<div>{props.title}</div>
);
import React, { Component } from 'react';
class Title extends Component {
render() {
return <div>{this.props.title}</div>
}
}
We have two ways of define a component:
UI part split into independent and reusable pieces
Props
Components & Props
Are single values or objects containing a set of values that are passed to React
Components on creation using a naming convention similar to HTML-tag
attributes.
<Input type="submit" value="Input value" />
UI part split into independent and reusable pieces
Admitted prop types?
Components & Props
const element = <Welcome
name="Sara" // Plain String
isLogged={false} // JavaScript expression
/>;
UI part split into independent and reusable pieces
How do we render a component?
Components & Props
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return <h1>Hello, this is my APP</h1>;
}
const element = <Welcome />;
ReactDOM.render(
element,
document.getElementById('root')
);
UI part split into independent and reusable pieces
How do we receive props in a component?
Components & Props
const UserCard = ({ name, age }) => (
<div>
<span>Hello, {name}</span>
<span>You're {age} years old</span>
</div>
);
const element = <UserCard
name="Sara"
age={28}
/>;
JavaScript function
class UserCard extends Component {
render() {
const { name, age } = this.props;
return (
<div>
<span>Hello, {name}</span>
<span>
You're {age} years old
</span>
</div>
);
}
}
ES6 Class
Components’ State & Lifecycle
FUNDAMENTALS
Information that influences the output of the render
How do we set a component’s initial state?
Components’ State & Lifecycle
class ComponentWithState extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
render() {
const { date } = this.state;
return (
<div>
<h1>It is {date.toLocaleTimeString()}</h1>
</div>
);
}
}
Class constructor
class ComponentWithState extends React.Component {
state = { date: new Date() };
render() {
const { date } = this.state;
return (
<div>
<h1>It is {date.toLocaleTimeString()}</h1>
</div>
);
}
}
Setting the property directly
Information that influences the output of the render
How do we update a component’s state?
Components’ State & Lifecycle
class ComponentWithState extends React.Component {
_toggleState = () => {
const { hasBeenClicked } = this.state;
this.setState({
hasBeenClicked: !hasBeenClicked
});
}
render() {
const { hasBeenClicked } = this.state;
return (
<div>
<h1>It has been clicked? {hasBeenClicked}.</h1>
<input type="button" onClick={this._toggleState} />
</div>
);
}
}
Using setState()
Information that influences the output of the render
Component’s lifecycle
Components’ State & Lifecycle
componentDidMount
shouldComponentUpdate
getDerivedStateFromProps
render
getSnaptshotBeforeUpdate
componentDidUpdate
componentWillUnmount
constructorConstructor
The constructor for a React component is called
before it is mounted.
The constructor is the right place to initialize state
and bind methods.
If you don’t need to initialize the state or bind
methods do not use constructor at all.
constructor
Information that influences the output of the render
Component’s lifecycle
Components’ State & Lifecycle
componentDidMount
shouldComponentUpdate
getDerivedStateFromProps
render
getSnaptshotBeforeUpdate
componentDidUpdate
componentWillUnmount
constructorComponentDidMount
Method invoked immediately after a component is
mounted.
Initialization that requires DOM nodes should go
here.
If you need to load data from a remote endpoint or
set up any subscription this is a good place to do it.
componentDidMount
Information that influences the output of the render
Component’s lifecycle
Components’ State & Lifecycle
componentDidMount
shouldComponentUpdate
getDerivedStateFromProps
render
getSnaptshotBeforeUpdate
componentDidUpdate
componentWillUnmount
constructorShouldComponentUpdate
Determinates if a component’s output needs to be
updated.
This method is invoked before rendering when new
props or state are being received. shouldComponentUpdate
Information that influences the output of the render
Component’s lifecycle
Components’ State & Lifecycle
componentDidMount
shouldComponentUpdate
getDerivedStateFromProps
render
getSnaptshotBeforeUpdate
componentDidUpdate
componentWillUnmount
constructorGetDerivedStateFromProps
Invoked on every render just before the render
method.
It should return an object to update the state or null
to not modify the state.
getDerivedStateFromProps
Information that influences the output of the render
Component’s lifecycle
Components’ State & Lifecycle
componentDidMount
shouldComponentUpdate
getDerivedStateFromProps
render
getSnaptshotBeforeUpdate
componentDidUpdate
componentWillUnmount
constructorrender
Method that should return an valid printable
element.
The return’s content will be the output that will be
printed in the DOM.
render
Information that influences the output of the render
Component’s lifecycle
Components’ State & Lifecycle
componentDidMount
shouldComponentUpdate
getDerivedStateFromProps
render
getSnaptshotBeforeUpdate
componentDidUpdate
componentWillUnmount
constructorgetSnaptshotBeforeUpdate
Invoked right before the most recently rendered
output is committed.
You’ll be able to capture component’s current
values before they are changed.
Any value returned will be passed as a parameter to
componentDidUpdate.
getSnaptshotBeforeUpdate
Information that influences the output of the render
Component’s lifecycle
Components’ State & Lifecycle
componentDidMount
shouldComponentUpdate
getDerivedStateFromProps
render
getSnaptshotBeforeUpdate
componentDidUpdate
componentWillUnmount
constructorcomponentDidUpdate
Invoked immediately after component update.
This is the place to operate on the DOM when the
component has been updated.
This is also a good place to do network requests.
componentDidUpdate
Information that influences the output of the render
Component’s lifecycle
Components’ State & Lifecycle
componentDidMount
shouldComponentUpdate
getDerivedStateFromProps
render
getSnaptshotBeforeUpdate
componentDidUpdate
componentWillUnmount
constructorcomponentWillUnmount
Invoked immediately before a component is
unmounted and destroyed.
This is the place to perform any necessary cleanup
(timers, network request, subscriptions…).
componentWillUnmount
Redux
“Redux is a predictable state container for JavaScript apps.”
BASIC REDUX FLOW
ACTIONS STORE REDUCERS
VIEW
ACTION,
PREVIOUS STATE
NEW STATE
DISPATCH(ACTION)
NEW STATE
INTERACTION
Actions
Payloads of information that send data to the store
ACTIONS STORE REDUCERS
VIEW
ACTION,
PREVIOUS STATE
NEW STATE
DISPATCH(ACTION)
NEW STATE
INTERACTION
Actions
Payloads of information that send data to the store
TYPE
ACTION
Type of the action being performed
Plain JS object with data
{
type: ADD_ITEM,
item: 'yourItem',
}
const ADD_ITEM = ‘ADD_ITEM';
ACTION CREATOR
Plain JS object with data
const addItem = (item) => ({
type: ADD_ITEM,
item,
});
Reducers
Specify how the app’s state changes in response to actions sent
ACTIONS STORE REDUCERS
VIEW
ACTION,
PREVIOUS STATE
NEW STATE
DISPATCH(ACTION)
NEW STATE
INTERACTION
Reducers
Specify how the app’s state changes in response to actions sent
function myReducer(state = initialState, action) {
switch (action.type) {
case SET_ITEM: {
// Do not mutate state
if (action.item === state.item) return state;
// Mutates state
return { ...state, item: action.item };
}
default: {
// Returining state or initial state the first time
return state
}
}
};
Store
Holds the state and have the control of the state
Initializing the store
ACTIONS STORE REDUCERS
VIEW
ACTION,
PREVIOUS STATE
NEW STATE
DISPATCH(ACTION)
NEW STATE
INTERACTION
Store
Holds the state and have the control of the state
// Optional parameter
const initialState = {};
// Application combined reducers
import reducers from './reducers';
const store = createStore(reducers, initialState)
Initializing the store
Store
Holds the state and have the control of the state
import {
addItem,
} from './actions'
// Get the application's state
store.getState();
// Add new item in store
store.dispatch(addItem('newItem'));
Dispatching actions
ACTIONS STORE REDUCERS
Presentational and Container Components
<i /> CLICK MEContainer Component Presentational Component
Manages UI.
DOM markup and styles.
Have no dependencies on the rest of the app.
Don’t care how store is designed.
Can have their own state (UI state).
Manages data.
Map the state to the presentational
component.
Map the actions to be dispatched by the UI.
Are usually generated using HOCs
(connect, createContainer…).
Container Components <i />
state = {
images: [
{
id: '010101’,
url: '/img/01.jpg’,
},
{
id: '010102’,
url: '/img/02.jpg’,
},
],
};
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import PicList from '../components/PicList';
import removeItem from '../actions';
const mapStateToProps = (state) => {
// Map state.
const { images } = state;
return { images };
};
const mapDispatchToProps = (dispatch) => ({
// Map actions.
removeItem: bindActionCreators(removeItem, dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(PicList);
export const removeItem = (id) => ({
type: REMOVE_ITEM,
id,
});
Presentational Components
import React from 'react';
import Image from '../Image';
export default function PicList(props) {
const { images = [], removeItem } = props;
return (
<div>
{images.map(({ url, id }) => (
<Image
key={id}
url={url}
onClick={() => { removeItem(id); }}
/>
))}
</div>
);
}
CLICK ME
Passing the store to the application
import React from 'react’;
import { render } from 'react-dom’;
import { Provider } from 'react-redux’;
import { createStore } from 'redux’;
import todoApp from './reducers’;
import App from './components/App’;
const store = createStore(todoApp);
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root’)
);
DEMO
¡Gracias!
Irene Foz && Sergio García
ifoz@pasiona.com
segarcia@pasiona.com

Más contenido relacionado

La actualidad más candente

GWT Training - Session 2/3
GWT Training - Session 2/3GWT Training - Session 2/3
GWT Training - Session 2/3Faiz Bashir
 
Introduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinIntroduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinSimon Gauvin
 
Design patterns in Magento
Design patterns in MagentoDesign patterns in Magento
Design patterns in MagentoDivante
 
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...Edureka!
 
Introduction to Vue.js
Introduction to Vue.jsIntroduction to Vue.js
Introduction to Vue.jsMeir Rotstein
 
Trustparency web doc spring 2.5 & hibernate
Trustparency web doc   spring 2.5 & hibernateTrustparency web doc   spring 2.5 & hibernate
Trustparency web doc spring 2.5 & hibernatetrustparency
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법Jeado Ko
 
Introduction to Everit Component Registry - B Zsoldos
Introduction to Everit Component Registry - B ZsoldosIntroduction to Everit Component Registry - B Zsoldos
Introduction to Everit Component Registry - B Zsoldosmfrancis
 
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
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin componentsPeter Lehto
 
Why SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScriptWhy SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScriptmartinlippert
 
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
 
GWT Training - Session 1/3
GWT Training - Session 1/3GWT Training - Session 1/3
GWT Training - Session 1/3Faiz Bashir
 
GWT Training - Session 3/3
GWT Training - Session 3/3GWT Training - Session 3/3
GWT Training - Session 3/3Faiz Bashir
 
Dagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionDagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionStfalcon Meetups
 

La actualidad más candente (20)

Solid angular
Solid angularSolid angular
Solid angular
 
GWT Training - Session 2/3
GWT Training - Session 2/3GWT Training - Session 2/3
GWT Training - Session 2/3
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
Introduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinIntroduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon Gauvin
 
Design patterns in Magento
Design patterns in MagentoDesign patterns in Magento
Design patterns in Magento
 
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
 
Introduction to Vue.js
Introduction to Vue.jsIntroduction to Vue.js
Introduction to Vue.js
 
Trustparency web doc spring 2.5 & hibernate
Trustparency web doc   spring 2.5 & hibernateTrustparency web doc   spring 2.5 & hibernate
Trustparency web doc spring 2.5 & hibernate
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 
Introduction to Everit Component Registry - B Zsoldos
Introduction to Everit Component Registry - B ZsoldosIntroduction to Everit Component Registry - B Zsoldos
Introduction to Everit Component Registry - B Zsoldos
 
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 17: EmberJS parte II
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte II
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin components
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
 
Why SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScriptWhy SOLID matters - even for JavaScript
Why SOLID matters - even for JavaScript
 
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
 
GWT Training - Session 1/3
GWT Training - Session 1/3GWT Training - Session 1/3
GWT Training - Session 1/3
 
Angular js-crash-course
Angular js-crash-courseAngular js-crash-course
Angular js-crash-course
 
GWT Training - Session 3/3
GWT Training - Session 3/3GWT Training - Session 3/3
GWT Training - Session 3/3
 
Dagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionDagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency Injection
 

Similar a React & Redux for noobs

Introduction to React for Frontend Developers
Introduction to React for Frontend DevelopersIntroduction to React for Frontend Developers
Introduction to React for Frontend DevelopersSergio Nakamura
 
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
 
Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017Elyse Kolker Gordon
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and SymfonyIgnacio Martín
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react jsdhanushkacnd
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
Combining Angular and React Together
Combining Angular and React TogetherCombining Angular and React Together
Combining Angular and React TogetherSebastian Pederiva
 
Introduction to React and MobX
Introduction to React and MobXIntroduction to React and MobX
Introduction to React and MobXAnjali Chawla
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today Nitin Tyagi
 
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Luciano Mammino
 
React: JSX and Top Level API
React: JSX and Top Level APIReact: JSX and Top Level API
React: JSX and Top Level APIFabio Biondi
 
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3Rob Tweed
 

Similar a React & Redux for noobs (20)

React outbox
React outboxReact outbox
React outbox
 
Introduction to React for Frontend Developers
Introduction to React for Frontend DevelopersIntroduction to React for Frontend Developers
Introduction to React for Frontend Developers
 
ReactJS
ReactJSReactJS
ReactJS
 
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 lecture
React lectureReact lecture
React lecture
 
Intro react js
Intro react jsIntro react js
Intro react js
 
Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017Building Universal Web Apps with React ForwardJS 2017
Building Universal Web Apps with React ForwardJS 2017
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and Symfony
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react js
 
Let's react - Meetup
Let's react - MeetupLet's react - Meetup
Let's react - Meetup
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
React redux
React reduxReact redux
React redux
 
React/Redux
React/ReduxReact/Redux
React/Redux
 
Combining Angular and React Together
Combining Angular and React TogetherCombining Angular and React Together
Combining Angular and React Together
 
Introduction to React and MobX
Introduction to React and MobXIntroduction to React and MobX
Introduction to React and MobX
 
React native by example by Vadim Ruban
React native by example by Vadim RubanReact native by example by Vadim Ruban
React native by example by Vadim Ruban
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
 
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
 
React: JSX and Top Level API
React: JSX and Top Level APIReact: JSX and Top Level API
React: JSX and Top Level API
 
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
 

Más de [T]echdencias

Transformacion digital, formacion y empleo
Transformacion digital, formacion y empleoTransformacion digital, formacion y empleo
Transformacion digital, formacion y empleo[T]echdencias
 
¡Bzz...! ¡Tienes una alerta!
¡Bzz...! ¡Tienes una alerta!¡Bzz...! ¡Tienes una alerta!
¡Bzz...! ¡Tienes una alerta![T]echdencias
 
Windows Template Studio by Martin Vega
Windows Template Studio by Martin Vega Windows Template Studio by Martin Vega
Windows Template Studio by Martin Vega [T]echdencias
 
Event Grid, colega que pasa en mi nube?
Event Grid, colega que pasa en mi nube?Event Grid, colega que pasa en mi nube?
Event Grid, colega que pasa en mi nube?[T]echdencias
 
#4Sessions - Azure Alerts - ¿Has probado a reiniciar?
#4Sessions - Azure Alerts - ¿Has probado a reiniciar?#4Sessions - Azure Alerts - ¿Has probado a reiniciar?
#4Sessions - Azure Alerts - ¿Has probado a reiniciar?[T]echdencias
 
Seamos 'Hipster', pensemos en ServerLess - Manu Delgado Díaz
Seamos 'Hipster', pensemos en ServerLess - Manu Delgado DíazSeamos 'Hipster', pensemos en ServerLess - Manu Delgado Díaz
Seamos 'Hipster', pensemos en ServerLess - Manu Delgado Díaz[T]echdencias
 
[Codemotion Madrid 2017] Como hacer una presentacion y no matar a la audiencia
[Codemotion Madrid 2017] Como hacer una presentacion y no matar a la audiencia[Codemotion Madrid 2017] Como hacer una presentacion y no matar a la audiencia
[Codemotion Madrid 2017] Como hacer una presentacion y no matar a la audiencia[T]echdencias
 
Power Users - Nueva experiencia Office 365
Power Users - Nueva experiencia Office 365 Power Users - Nueva experiencia Office 365
Power Users - Nueva experiencia Office 365 [T]echdencias
 
Node.js + Azure, o como mezclar agua con aceite
Node.js + Azure, o como mezclar agua con aceite Node.js + Azure, o como mezclar agua con aceite
Node.js + Azure, o como mezclar agua con aceite [T]echdencias
 
Testear videojuegos con Unity3D
Testear videojuegos con Unity3D Testear videojuegos con Unity3D
Testear videojuegos con Unity3D [T]echdencias
 
The big ball of mud | 4Sessions Feb17
The big ball of mud | 4Sessions Feb17The big ball of mud | 4Sessions Feb17
The big ball of mud | 4Sessions Feb17[T]echdencias
 
DevOps - Más allá del botón derecho > publicar | 4Sessions Feb17
DevOps -  Más allá del botón derecho > publicar | 4Sessions Feb17DevOps -  Más allá del botón derecho > publicar | 4Sessions Feb17
DevOps - Más allá del botón derecho > publicar | 4Sessions Feb17[T]echdencias
 
Primer vistazo al computer vision | 4Sessions Feb17
Primer vistazo al computer vision | 4Sessions Feb17Primer vistazo al computer vision | 4Sessions Feb17
Primer vistazo al computer vision | 4Sessions Feb17[T]echdencias
 
Arduino para seres humanos | 4Sessions Feb17
Arduino para seres humanos | 4Sessions Feb17Arduino para seres humanos | 4Sessions Feb17
Arduino para seres humanos | 4Sessions Feb17[T]echdencias
 
2D zombies survival game | Codemotion 2016
2D zombies survival game | Codemotion 20162D zombies survival game | Codemotion 2016
2D zombies survival game | Codemotion 2016[T]echdencias
 
Application Insight + stream analytics + Power BI
Application Insight + stream analytics + Power BIApplication Insight + stream analytics + Power BI
Application Insight + stream analytics + Power BI[T]echdencias
 
Botón derecho --> publicar
Botón derecho --> publicarBotón derecho --> publicar
Botón derecho --> publicar[T]echdencias
 

Más de [T]echdencias (20)

Transformacion digital, formacion y empleo
Transformacion digital, formacion y empleoTransformacion digital, formacion y empleo
Transformacion digital, formacion y empleo
 
I get the Power BI
I get the Power BII get the Power BI
I get the Power BI
 
Selenium + docker
Selenium + dockerSelenium + docker
Selenium + docker
 
Azure Logic Apps
Azure Logic Apps Azure Logic Apps
Azure Logic Apps
 
¡Bzz...! ¡Tienes una alerta!
¡Bzz...! ¡Tienes una alerta!¡Bzz...! ¡Tienes una alerta!
¡Bzz...! ¡Tienes una alerta!
 
Windows Template Studio by Martin Vega
Windows Template Studio by Martin Vega Windows Template Studio by Martin Vega
Windows Template Studio by Martin Vega
 
Event Grid, colega que pasa en mi nube?
Event Grid, colega que pasa en mi nube?Event Grid, colega que pasa en mi nube?
Event Grid, colega que pasa en mi nube?
 
#4Sessions - Azure Alerts - ¿Has probado a reiniciar?
#4Sessions - Azure Alerts - ¿Has probado a reiniciar?#4Sessions - Azure Alerts - ¿Has probado a reiniciar?
#4Sessions - Azure Alerts - ¿Has probado a reiniciar?
 
Seamos 'Hipster', pensemos en ServerLess - Manu Delgado Díaz
Seamos 'Hipster', pensemos en ServerLess - Manu Delgado DíazSeamos 'Hipster', pensemos en ServerLess - Manu Delgado Díaz
Seamos 'Hipster', pensemos en ServerLess - Manu Delgado Díaz
 
[Codemotion Madrid 2017] Como hacer una presentacion y no matar a la audiencia
[Codemotion Madrid 2017] Como hacer una presentacion y no matar a la audiencia[Codemotion Madrid 2017] Como hacer una presentacion y no matar a la audiencia
[Codemotion Madrid 2017] Como hacer una presentacion y no matar a la audiencia
 
Power Users - Nueva experiencia Office 365
Power Users - Nueva experiencia Office 365 Power Users - Nueva experiencia Office 365
Power Users - Nueva experiencia Office 365
 
Node.js + Azure, o como mezclar agua con aceite
Node.js + Azure, o como mezclar agua con aceite Node.js + Azure, o como mezclar agua con aceite
Node.js + Azure, o como mezclar agua con aceite
 
Testear videojuegos con Unity3D
Testear videojuegos con Unity3D Testear videojuegos con Unity3D
Testear videojuegos con Unity3D
 
The big ball of mud | 4Sessions Feb17
The big ball of mud | 4Sessions Feb17The big ball of mud | 4Sessions Feb17
The big ball of mud | 4Sessions Feb17
 
DevOps - Más allá del botón derecho > publicar | 4Sessions Feb17
DevOps -  Más allá del botón derecho > publicar | 4Sessions Feb17DevOps -  Más allá del botón derecho > publicar | 4Sessions Feb17
DevOps - Más allá del botón derecho > publicar | 4Sessions Feb17
 
Primer vistazo al computer vision | 4Sessions Feb17
Primer vistazo al computer vision | 4Sessions Feb17Primer vistazo al computer vision | 4Sessions Feb17
Primer vistazo al computer vision | 4Sessions Feb17
 
Arduino para seres humanos | 4Sessions Feb17
Arduino para seres humanos | 4Sessions Feb17Arduino para seres humanos | 4Sessions Feb17
Arduino para seres humanos | 4Sessions Feb17
 
2D zombies survival game | Codemotion 2016
2D zombies survival game | Codemotion 20162D zombies survival game | Codemotion 2016
2D zombies survival game | Codemotion 2016
 
Application Insight + stream analytics + Power BI
Application Insight + stream analytics + Power BIApplication Insight + stream analytics + Power BI
Application Insight + stream analytics + Power BI
 
Botón derecho --> publicar
Botón derecho --> publicarBotón derecho --> publicar
Botón derecho --> publicar
 

Último

Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
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
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
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
 
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
 
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
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
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
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 

Último (20)

Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
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
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
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
 
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)
 
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...
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
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
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 

React & Redux for noobs

  • 1. React & Redux for noobs
  • 2. SERGIO GARCÍA SANTOS FRONT END DEVELOPER @sgarcias95 segarcia@pasiona.com
  • 3. IRENE FOZ ALMAGRO FRONT END DEVELOPER @ireefoz10 ifoz@pasiona.com
  • 5. “A JavaScript library for building user interfaces”
  • 6. COMPONENT-BASED UI part split into independent and reusable pieces
  • 7.
  • 9. React Native Build native mobile apps using JS and React iOS Android
  • 10. EFFICIENCY Updating the browser’s displayed DOM efficiently
  • 11. .root .header .body .content.links.logo .welcome .list .form VirtualDOM Updating the browser’s displayed DOM efficiently
  • 12. .root .header .body .content.links.logo .welcome .list .form VirtualDOM Updating the browser’s displayed DOM efficiently .root .header .body .content.links.logo .welcome .list .form .welcome .form CALCULATES DIFFERENCES
  • 13. .root .header .body .content.links.logo .welcome .list .form VirtualDOM Updating the browser’s displayed DOM efficiently .root .header .body .content.links.logo .welcome .list .form .welcome .form APPLIES THEM .form .welcome
  • 17. JSX Sugar syntax for the React.createElement() function. <MyButton color="blue" shadowSize={2}> Click Me </MyButton> React.createElement( MyButton, { color: 'blue', shadowSize: 2 }, 'Click Me' )
  • 18. JSX Sugar syntax for the React.createElement() function. React library must always be in scope from your JSX file import React from 'react'; import { Link as DomLink } from 'react-router-dom'; const Link = ({ to, className, children }) => ( <DomLink to={to || '/'}>{children} </DomLink>, ); export default Link;
  • 19. JSX Sugar syntax for the React.createElement() function. Your components’ name must be Capitalized import React from 'react'; import { Link as DomLink } from 'react-router-dom'; // Good const Link = ({ to, className, children }) => ( <DomLink to={to || '/'}>{children}</DomLink> ); // Wrong! const link = ({ to, className, children }) => ( <DomLink to={to || '/'}>{children}</DomLink> );
  • 20. JSX Sugar syntax for the React.createElement() function. Use camel case for JSX types import React from 'react'; import { Link as DomLink } from 'react-router-dom'; // Good const LinkToHome = ({ to, className, children }) => ( <DomLink to={to || '/'}>{children}</DomLink> ); // Wrong! const Linktohome = ({ to, className, children }) => ( <DomLink to={to || '/'}>{children}</DomLink> );
  • 21. JSX Sugar syntax for the React.createElement() function. Not use general expressions as React element type import React from 'react'; import { Link as DomLink } from 'react-router-dom’; const links = { tree: Tree, spinner: Spinner }; // Good const MockImage = ({ type }) => { const Image = links[type]; return <Image /> }; // Wrong! const MockImage = ({ type }) => ( <links[type] /> );
  • 22. JSX Sugar syntax for the React.createElement() function. Component’s children const Example = () => (<div>Hello</div>); /* Output: * ------------------------ * Hello * ------------------------ */ String Literals Other components Javascript Expressions Functions Boolean, undefined or null
  • 23. JSX Sugar syntax for the React.createElement() function. Component’s children const CustomComponent = ({ src }) => ('This is the CustomComponent’s child'); const Example = ({ src }) => (<CustomComponent />); /* Output: * ------------------------ * This is the CustomComponent’s child * ------------------------ */ String Literals Other components Javascript Expressions Functions Boolean, undefined or null
  • 24. JSX Sugar syntax for the React.createElement() function. Component’s children const First = () => 'Hello'; // Hello const _users = ['Pepe', 'Antonio']; const Second = () => _users.map((user) => (user)); // PepeAntonio const Third = () => <div>Hello {users[0]}</div> // Hello Pepe Other componentsString Literals Javascript Expressions Functions Boolean, undefined or null
  • 25. JSX Sugar syntax for the React.createElement() function. Component’s children const users = ['Pepe', 'Antonio']; const getComponentChildren = () => { return users.map((user) => <div>Hello user: {user}</div>); } const Component = () => getComponentChildren(); // Hello user: Pepe // Hello user: Antonio String Literals Other components Javascript Expressions Functions Boolean, undefined or null
  • 26. JSX Sugar syntax for the React.createElement() function. Component’s children const NullComponent = () => null; // const BooleanComponent = () => true; // const UndefinedComponent = () => undefined; // String Literals Other components Javascript Expressions Functions Boolean, undefined or null
  • 28. React Components UI part split into independent and reusable pieces
  • 29. JavaScript function ES6 Class import React from 'react'; const Title = (props) => ( <div>{props.title}</div> ); import React, { Component } from 'react'; class Title extends Component { render() { return <div>{this.props.title}</div> } } We have two ways of define a component:
  • 30. UI part split into independent and reusable pieces Props Components & Props Are single values or objects containing a set of values that are passed to React Components on creation using a naming convention similar to HTML-tag attributes. <Input type="submit" value="Input value" />
  • 31. UI part split into independent and reusable pieces Admitted prop types? Components & Props const element = <Welcome name="Sara" // Plain String isLogged={false} // JavaScript expression />;
  • 32. UI part split into independent and reusable pieces How do we render a component? Components & Props import React from 'react'; import ReactDOM from 'react-dom'; function App() { return <h1>Hello, this is my APP</h1>; } const element = <Welcome />; ReactDOM.render( element, document.getElementById('root') );
  • 33. UI part split into independent and reusable pieces How do we receive props in a component? Components & Props const UserCard = ({ name, age }) => ( <div> <span>Hello, {name}</span> <span>You're {age} years old</span> </div> ); const element = <UserCard name="Sara" age={28} />; JavaScript function class UserCard extends Component { render() { const { name, age } = this.props; return ( <div> <span>Hello, {name}</span> <span> You're {age} years old </span> </div> ); } } ES6 Class
  • 34. Components’ State & Lifecycle FUNDAMENTALS
  • 35. Information that influences the output of the render How do we set a component’s initial state? Components’ State & Lifecycle class ComponentWithState extends React.Component { constructor(props) { super(props); this.state = { date: new Date() }; } render() { const { date } = this.state; return ( <div> <h1>It is {date.toLocaleTimeString()}</h1> </div> ); } } Class constructor class ComponentWithState extends React.Component { state = { date: new Date() }; render() { const { date } = this.state; return ( <div> <h1>It is {date.toLocaleTimeString()}</h1> </div> ); } } Setting the property directly
  • 36. Information that influences the output of the render How do we update a component’s state? Components’ State & Lifecycle class ComponentWithState extends React.Component { _toggleState = () => { const { hasBeenClicked } = this.state; this.setState({ hasBeenClicked: !hasBeenClicked }); } render() { const { hasBeenClicked } = this.state; return ( <div> <h1>It has been clicked? {hasBeenClicked}.</h1> <input type="button" onClick={this._toggleState} /> </div> ); } } Using setState()
  • 37. Information that influences the output of the render Component’s lifecycle Components’ State & Lifecycle componentDidMount shouldComponentUpdate getDerivedStateFromProps render getSnaptshotBeforeUpdate componentDidUpdate componentWillUnmount constructorConstructor The constructor for a React component is called before it is mounted. The constructor is the right place to initialize state and bind methods. If you don’t need to initialize the state or bind methods do not use constructor at all. constructor
  • 38. Information that influences the output of the render Component’s lifecycle Components’ State & Lifecycle componentDidMount shouldComponentUpdate getDerivedStateFromProps render getSnaptshotBeforeUpdate componentDidUpdate componentWillUnmount constructorComponentDidMount Method invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint or set up any subscription this is a good place to do it. componentDidMount
  • 39. Information that influences the output of the render Component’s lifecycle Components’ State & Lifecycle componentDidMount shouldComponentUpdate getDerivedStateFromProps render getSnaptshotBeforeUpdate componentDidUpdate componentWillUnmount constructorShouldComponentUpdate Determinates if a component’s output needs to be updated. This method is invoked before rendering when new props or state are being received. shouldComponentUpdate
  • 40. Information that influences the output of the render Component’s lifecycle Components’ State & Lifecycle componentDidMount shouldComponentUpdate getDerivedStateFromProps render getSnaptshotBeforeUpdate componentDidUpdate componentWillUnmount constructorGetDerivedStateFromProps Invoked on every render just before the render method. It should return an object to update the state or null to not modify the state. getDerivedStateFromProps
  • 41. Information that influences the output of the render Component’s lifecycle Components’ State & Lifecycle componentDidMount shouldComponentUpdate getDerivedStateFromProps render getSnaptshotBeforeUpdate componentDidUpdate componentWillUnmount constructorrender Method that should return an valid printable element. The return’s content will be the output that will be printed in the DOM. render
  • 42. Information that influences the output of the render Component’s lifecycle Components’ State & Lifecycle componentDidMount shouldComponentUpdate getDerivedStateFromProps render getSnaptshotBeforeUpdate componentDidUpdate componentWillUnmount constructorgetSnaptshotBeforeUpdate Invoked right before the most recently rendered output is committed. You’ll be able to capture component’s current values before they are changed. Any value returned will be passed as a parameter to componentDidUpdate. getSnaptshotBeforeUpdate
  • 43. Information that influences the output of the render Component’s lifecycle Components’ State & Lifecycle componentDidMount shouldComponentUpdate getDerivedStateFromProps render getSnaptshotBeforeUpdate componentDidUpdate componentWillUnmount constructorcomponentDidUpdate Invoked immediately after component update. This is the place to operate on the DOM when the component has been updated. This is also a good place to do network requests. componentDidUpdate
  • 44. Information that influences the output of the render Component’s lifecycle Components’ State & Lifecycle componentDidMount shouldComponentUpdate getDerivedStateFromProps render getSnaptshotBeforeUpdate componentDidUpdate componentWillUnmount constructorcomponentWillUnmount Invoked immediately before a component is unmounted and destroyed. This is the place to perform any necessary cleanup (timers, network request, subscriptions…). componentWillUnmount
  • 45. Redux
  • 46. “Redux is a predictable state container for JavaScript apps.”
  • 47. BASIC REDUX FLOW ACTIONS STORE REDUCERS VIEW ACTION, PREVIOUS STATE NEW STATE DISPATCH(ACTION) NEW STATE INTERACTION
  • 48. Actions Payloads of information that send data to the store ACTIONS STORE REDUCERS VIEW ACTION, PREVIOUS STATE NEW STATE DISPATCH(ACTION) NEW STATE INTERACTION
  • 49. Actions Payloads of information that send data to the store TYPE ACTION Type of the action being performed Plain JS object with data { type: ADD_ITEM, item: 'yourItem', } const ADD_ITEM = ‘ADD_ITEM'; ACTION CREATOR Plain JS object with data const addItem = (item) => ({ type: ADD_ITEM, item, });
  • 50. Reducers Specify how the app’s state changes in response to actions sent ACTIONS STORE REDUCERS VIEW ACTION, PREVIOUS STATE NEW STATE DISPATCH(ACTION) NEW STATE INTERACTION
  • 51. Reducers Specify how the app’s state changes in response to actions sent function myReducer(state = initialState, action) { switch (action.type) { case SET_ITEM: { // Do not mutate state if (action.item === state.item) return state; // Mutates state return { ...state, item: action.item }; } default: { // Returining state or initial state the first time return state } } };
  • 52. Store Holds the state and have the control of the state Initializing the store ACTIONS STORE REDUCERS VIEW ACTION, PREVIOUS STATE NEW STATE DISPATCH(ACTION) NEW STATE INTERACTION
  • 53. Store Holds the state and have the control of the state // Optional parameter const initialState = {}; // Application combined reducers import reducers from './reducers'; const store = createStore(reducers, initialState) Initializing the store
  • 54. Store Holds the state and have the control of the state import { addItem, } from './actions' // Get the application's state store.getState(); // Add new item in store store.dispatch(addItem('newItem')); Dispatching actions ACTIONS STORE REDUCERS
  • 55.
  • 56. Presentational and Container Components <i /> CLICK MEContainer Component Presentational Component Manages UI. DOM markup and styles. Have no dependencies on the rest of the app. Don’t care how store is designed. Can have their own state (UI state). Manages data. Map the state to the presentational component. Map the actions to be dispatched by the UI. Are usually generated using HOCs (connect, createContainer…).
  • 57. Container Components <i /> state = { images: [ { id: '010101’, url: '/img/01.jpg’, }, { id: '010102’, url: '/img/02.jpg’, }, ], }; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import PicList from '../components/PicList'; import removeItem from '../actions'; const mapStateToProps = (state) => { // Map state. const { images } = state; return { images }; }; const mapDispatchToProps = (dispatch) => ({ // Map actions. removeItem: bindActionCreators(removeItem, dispatch), }); export default connect(mapStateToProps, mapDispatchToProps)(PicList); export const removeItem = (id) => ({ type: REMOVE_ITEM, id, });
  • 58. Presentational Components import React from 'react'; import Image from '../Image'; export default function PicList(props) { const { images = [], removeItem } = props; return ( <div> {images.map(({ url, id }) => ( <Image key={id} url={url} onClick={() => { removeItem(id); }} /> ))} </div> ); } CLICK ME
  • 59. Passing the store to the application import React from 'react’; import { render } from 'react-dom’; import { Provider } from 'react-redux’; import { createStore } from 'redux’; import todoApp from './reducers’; import App from './components/App’; const store = createStore(todoApp); render( <Provider store={store}> <App /> </Provider>, document.getElementById('root’) );
  • 60. DEMO
  • 61. ¡Gracias! Irene Foz && Sergio García ifoz@pasiona.com segarcia@pasiona.com

Notas del editor

  1. IRENE
  2. IRENE
  3. SERGIO
  4. SERGIO
  5. IRENE
  6. IRENE
  7. SERGIO
  8. SERGIO
  9. SERGIO
  10. SERGIO
  11. IRENE
  12. IRENE
  13. IRENE
  14. IRENE
  15. IRENE
  16. SERGIO
  17. SERGIO
  18. SERGIO
  19. IRENE
  20. SERGIO
  21. IRENE
  22. SERGIO
  23. IRENE
  24. SERGIO
  25. SERGIO
  26. SERGIO
  27. IRENE
  28. IRENE
  29. IRENE
  30. IRENE
  31. SERGIO
  32. SERGIO
  33. SERGIO
  34. SERGIO
  35. IRENE
  36. SERGIO
  37. IRENE
  38. SERGIO
  39. IRENE
  40. SERGIO
  41. IRENE
  42. IRENE
  43. IRENE
  44. SERGIO
  45. IRENE
  46. IRENE
  47. IRENE
  48. IRENE
  49. SERGIO
  50. SERGIO
  51. SERGIO
  52. IRENE
  53. IRENE – CONTAINER COMPONENT SERGIO – PRESENTATIONAL COMPONENT
  54. IRENE
  55. SERGIO
  56. IRENE