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
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
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
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…).
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’)
);