React + Flux + Redux Basics
Meet React
A JavaScript Library for Building User Interfaces
React is only the view layer
Virtual DOM
What about the code?
Create-react-app
Create React apps with no build configuration.
// Install it globally
npm install -g create-react-app
// Creates new React app
create-react-app my-app
cd my-app
// Runs app in development mode.
// Server listening on localhost:8080
npm start
// Builds the app for production
npm run build
Render method
Render a React Element into the DOM
ReactDOM.render(
<h1>Hello world!</h1>, // Element
document.getElementById('root') // Root node container
);
Our first component
See the PenReact Render Method - Example by Param-Harrison (@Param-Harrison) onCodePen.
Components
Fundamental block of UI
React.createClass({
render: function() {
return <h1>Hello world!</h1>
}
});
- A React Component let you split the UI into independent, reusable pieces, and think about each piece in isolation.
Component definition
Using createClass method
var Title = React.createClass({
render: function() {
return <h1>Hello world!</h1>
}
});
Using ES6 classes
class Title extends React.Component {
render() {
return <h1>Hello world!</h1>
}
}
ES6 way is preferable combined with WebpackTo sum up
Create the component
var Title = React.createClass({
render: function() {
return <h1>Hello world!</h1>
}
});
And render it into the DOM
ReactDOM.render(
<Title/>,
document.getElementById('root')
);
Our first component
See the PenReact Simple Component by Param-Harrison (@Param-Harrison) onCodePen.
That's great, but...
Is that HTML inside our JS?
JSX
Not exactly, It's preprocessor with HTML-like syntax. More like EJS, HAML, Handlebar templates
React.createClass({
render: function() {
return <h1>Hello world!</h1>
}
});
React.createClass({
render: function() {
return React.createElement(
'h1', // Element type
null, // Props
"Hello world!" // Children
)
}
});
JSX Gotchas
Component props
Read-only properties passed to a React Component via its attributes
We can access these properties inside the components via the this.props object
<Title
color="red"
fontSize="2em"
hidden={true}
/>
this.props = {
color: 'red',
fontSize: '2em',
hidden: true,
// ...
}
PropTypes
They define what props your Component needs and what type(s) they should be
The isRequired property tells that the property is required for the Component to work
Using createClass method
var Series = React.createClass({
propTypes: {
name: React.PropTypes.string.isRequired,
seasons: React.PropTypes.number
},
render: function() { /* ... */ }
});
Using ES6 classes
class Series extends React.Component {
render() { /* ... */ }
}
Series.propTypes = {
name: React.PropTypes.string.isRequired,
seasons: React.PropTypes.number
}
JS primitive types
- array
- bool
- func
- number
- object
- string
- symbol
Others
- node
- element
- instanceOf()
- oneOf([])
- oneOfType([])
- arrayOf()
- objectOf()
- shape({})
- any
DefaultProps
They define props default values in case they are not passed in
Using createClass method
var Series = React.createClass({
defaultProps: {
name: 'Game of Thrones'
seasons: 1
},
render: function() { /* ... */ }
});
Using ES6 classes
class Series extends React.Component {
render() { /* ... */ }
}
Series.defaultProps = {
name: 'Game of Thrones'
seasons: 1
}
See the Pen React Props - Example by Param-Harrison (@Param-Harrison) on CodePen.
Component state
Initial state
Using createClass method
var Series = React.createClass({
getInitialState: function() {
return {
likes: 0,
// ...
}
},
render: function() { /* ... */ }
});
Using ES6 classes
class Series extends React.Component {
constructor(props) {
super(props);
this.state = {
likes: 0,
//...
}
}
render() { /* ... */ }
}
Change component state
setState Method
this.setState(nextState);
- Primary method to trigger UI updates unless shouldComponentUpdate() is false
- Merge the nextState into current state
Example
var Series = React.createClass({
getInitialState: function() {
return { likes: 0, /* ... */ }
},
like: function() {
this.setState({
likes: this.state.likes + 1
})
},
//...
});
See the Pen React State - Example by Param-Harrison (@Param-Harrison) on CodePen.
Component lifecycle
Lifecycle callbacks
class component extends React.Component {
// called before the render method is executed
componentWillMount() { /* ... */ },
// called as soon as the render method is executed
componentDidMount() { /* ... */ },
// called first when props or state changed
componentWillReceiveProps(nextProps) { /* ... */ },
// if a re-rendering is needed or can be skipped
shouldComponentUpdate(nextProps, nextState) { /* ... */ },
// called as soon as the `shouldComponentUpdate` return true
componentWillUpdate(nextProps, nextState) { /* ... */ },
componentDidUpdate(nextProps, nextState) { /* ... */ },
componentWillUnmount() { /* ... */ },
render() { /* ... */ }
};
See the Pen React Lifecycle - Example by Param-Harrison (@Param-Harrison) on CodePen.
Flux
Flux is more of a pattern than a framework
Data flow
Flux cartoon guide by @linclark
User triggers an action
View tells the Action Creator to prepare the action
Action Creator formats the action and dispatch it
Dispatcher sends the action to the stores
Stores change the state and notifiy subscribed views controllers
View Controller ask for new state and updates the view
See the Pen React + Flux - Example by Param-Harrison (@Param-Harrison) on CodePen.
`Meet Redux
Single source of truth
1st principle of Redux
The whole state of your app is stored in an object tree inside a single store
State
{
SeriesArray: [
{
id: 1,
name: 'Game of Thrones',
seasons: 6,
likes: 0
},
// ...
]
}
2nd principle of Redux
The state is read-only. The only way to change the state tree is to emit an action, an object describing what happened.
Action
Minimal representation of a state change
{
type: 'LIKE', // Type is mandatory
Series_id: 1,
// ...
}
3rd principle of Redux - Reducer function
Pure function that describes how the state mutates based on the given action
Pure functions
1 - Output depends only on the given arguments
2 - Function doesn't mutate arguments
function append(array, item) {
item = api_call(item);
return array.push(item);
}
function append(array, item) {
return array.concat(item);
}
Array.reduce((accumulator, value) => accumulator)
Array.reduce((accumulator, value) => accumulator)
reducer(state, action) => state
const reducer = (state = 0, action) => {
switch(action.type) {
case 'LIKE':
return state + action.increment
default:
return state;
}
}
Store
Binds Redux principles into one object
const store = Redux.createStore(reducer)
Store main methods
getState()
Returns: current state
dispatch(action)
Arguments: action to be dispatched
Returns: dispatched action
subscribe(callback)
Arguments: callback that will be called any time an action is dispatched
See the Pen React + Redux example by Param-Harrison (@Param-Harrison) on CodePen.
Simple Todo App - React + Redux
See the Pen React + Redux example by Param-Harrison (@Param-Harrison) on CodePen.