SlideShare a Scribd company logo
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
React & Redux for noobs
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
React & Redux for noobs
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

More Related Content

PDF
JSLab. Алексей Волков. "React на практике"
PPTX
Angular modules in depth
PPTX
Angular Workshop_Sarajevo2
PPTX
AngularJs-training
PPTX
React 16: new features and beyond
PPTX
Extend sdk
PDF
Get AngularJS Started!
PDF
Workshop 20: ReactJS Part II Flux Pattern & Redux
JSLab. Алексей Волков. "React на практике"
Angular modules in depth
Angular Workshop_Sarajevo2
AngularJs-training
React 16: new features and beyond
Extend sdk
Get AngularJS Started!
Workshop 20: ReactJS Part II Flux Pattern & Redux

What's hot (20)

PDF
Solid angular
PPT
GWT Training - Session 2/3
PPTX
Angular2 + rxjs
PDF
Introduction to Polymer and Firebase - Simon Gauvin
PDF
Design patterns in Magento
PDF
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
PDF
Introduction to Vue.js
PDF
Trustparency web doc spring 2.5 & hibernate
PDF
[FEConf Korea 2017]Angular 컴포넌트 대화법
ODP
Introduction to Everit Component Registry - B Zsoldos
PDF
Workshop 27: Isomorphic web apps with ReactJS
PDF
Workshop 17: EmberJS parte II
PDF
Binding business data to vaadin components
PDF
AngularJS Basic Training
PDF
Why SOLID matters - even for JavaScript
PDF
Workshop 26: React Native - The Native Side
PPT
GWT Training - Session 1/3
ODP
Angular js-crash-course
PPT
GWT Training - Session 3/3
PDF
Dagger 2. Right way to do Dependency Injection
Solid angular
GWT Training - Session 2/3
Angular2 + rxjs
Introduction to Polymer and Firebase - Simon Gauvin
Design patterns in Magento
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
Introduction to Vue.js
Trustparency web doc spring 2.5 & hibernate
[FEConf Korea 2017]Angular 컴포넌트 대화법
Introduction to Everit Component Registry - B Zsoldos
Workshop 27: Isomorphic web apps with ReactJS
Workshop 17: EmberJS parte II
Binding business data to vaadin components
AngularJS Basic Training
Why SOLID matters - even for JavaScript
Workshop 26: React Native - The Native Side
GWT Training - Session 1/3
Angular js-crash-course
GWT Training - Session 3/3
Dagger 2. Right way to do Dependency Injection
Ad

Similar to React & Redux for noobs (20)

PPTX
Dyanaimcs of business and economics unit 2
PPTX
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
PDF
unit 3_Adv WTAdvanced Web Tecg Design_HTML_CSS_JAVASCRIPT_AJAX_PPT.pdf
PPTX
ReactJS (1)
PDF
Stay with React.js in 2020
PPTX
React workshop
PPTX
React - Start learning today
PPT
PDF
Welcome to React & Flux !
PPTX
Unit 2 Fundamentals of React -------.pptx
PDF
Full Stack React Workshop [CSSC x GDSC]
PDF
React js
PPTX
React Workshop: Core concepts of react
PPTX
2.React tttttttttttttttttttttttttttttttt
PDF
ReactJS presentation
PDF
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
PDF
Fundamental concepts of react js
PPTX
class based component.pptx
PPTX
Introduction to React JS.pptx
PPTX
[Final] ReactJS presentation
Dyanaimcs of business and economics unit 2
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
unit 3_Adv WTAdvanced Web Tecg Design_HTML_CSS_JAVASCRIPT_AJAX_PPT.pdf
ReactJS (1)
Stay with React.js in 2020
React workshop
React - Start learning today
Welcome to React & Flux !
Unit 2 Fundamentals of React -------.pptx
Full Stack React Workshop [CSSC x GDSC]
React js
React Workshop: Core concepts of react
2.React tttttttttttttttttttttttttttttttt
ReactJS presentation
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Fundamental concepts of react js
class based component.pptx
Introduction to React JS.pptx
[Final] ReactJS presentation
Ad

More from [T]echdencias (20)

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

Recently uploaded (20)

PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
Online Work Permit System for Fast Permit Processing
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
System and Network Administraation Chapter 3
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
AI in Product Development-omnex systems
PPT
Introduction Database Management System for Course Database
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
medical staffing services at VALiNTRY
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
Introduction to Artificial Intelligence
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
VVF-Customer-Presentation2025-Ver1.9.pptx
Online Work Permit System for Fast Permit Processing
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
System and Network Administraation Chapter 3
Operating system designcfffgfgggggggvggggggggg
Upgrade and Innovation Strategies for SAP ERP Customers
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Adobe Illustrator 28.6 Crack My Vision of Vector Design
CHAPTER 2 - PM Management and IT Context
AI in Product Development-omnex systems
Introduction Database Management System for Course Database
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Softaken Excel to vCard Converter Software.pdf
medical staffing services at VALiNTRY
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Introduction to Artificial Intelligence

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
  • 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
  • 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

Editor's Notes