Reactjs Workshop

Go to slides

Introduction concepts

  • What is react.js?
  • What problems solve?
  • What is JSX
  • What is Virtual DOM and why it matters?

How Virtual-DOM and diffing works in React


create-react-app

Just a quickstart script to start coding reactjs.

1
2
3
4
npm install -g create-react-app
create-react-app my-app
cd my-app
npm start

What create-react-app does behind the scenes?

Create react app is a generator which creates skeleton application ready to start to develop your react.js project. The generated application handles the next parts:


  • It creates folders and files structures with a very basic and functional react project.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
my-app
├── README.html
├── node_modules
├── package.json
├── .gitignore
├── public
│ └── favicon.ico
│ └── index.html
│ └── manifest.json
└── src
└── App.css
└── App.js
└── App.test.js
└── index.css
└── index.js
└── logo.svg
└── registerServiceWorker.js

  • It comes with some predefined scripts to work with your reactjs application:
    • yarn start: Starts the development server.
    • yarn build: Builds a packaged version of your application to be distributed.
    • yarn test: Runs your application test suites.
    • yarn eject: (Advanced).
  • Among these scripts, it also handles webpack configuration.
  • It installs all needed dependencies to start to work :)

About components

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.


Anatomy of a Component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// A React.js component is just a ES6 class extending React.Component
// It should implement at least the render method
class Calculator extends React.Component {
// You have a constructor receiving the props as parameters
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.state = {temperature: ''}
}

handleChange(e) {
this.setState({temperature: e.target.value})
}

// The render method is called each time the state of component changes
render() {
const { temperature } = this.state
// Wow! what's here? Html code inside a javascript file.
// This language is called JSX
// More info at https://reactjs.org/docs/jsx-in-depth.html
return (
<fieldset>
<legend>Enter temperature in Celsius:</legend>
<input
value={temperature}
onChange={this.handleChange} />
<BoilingVerdict
celsius={parseFloat(temperature)} />
</fieldset>
);
}
}

// Exporting the react component class to be included
export default Calculator

Exercise

  • Create a new Component called Counter rendering a simple text.
  • Include your new component in App.js component and add it inside render method using JSX.
  • Save all files and see what’s happening in your browser.

About component state and lifecycle

  • setState() schedules an update to a component’s state object. When the state changes, the component responds by re-rendering.

State and Lifecycle


  • A React component is like a state machine that represents an user interface. Every user action potentially triggers a change in that state machine. Then, the new state is represented by a different React element.

How to handle state in React. The missing FAQ.


  • State, like with React props, is used to store data in React. A difference between state and props is that while the data stored by props is fixed throughout its lifetime, state stores data that can be changed overtime. This change can be in response to user actions, network responses or anything. Also, while props are set by the parent component, state is changed internally by the component itself.

Understanding State in React Components


Exercise

  • Initialize your component using its constructor and set the state with a variable to store the number of clicks initialized with 0.
  • Create a class method to increment the number of clicks using setState.
    • NOTE you can access previous state calling this.state.variableName.
  • Add a button in your render method which call the method created to increment state.
  • Add a text printing the value of the increment
  • Save all and play with your new counter button.

More info


About component props

Most components can be customized when they are created, with different parameters. These creation parameters are called props.

Props


Passing props to component:

1
<Image source={pic} style={{width: 193, height: 110}} />

The value of pic is sent to source prop. In style we’re sending an object directly.


Getting the props from component

1
2
3
4
5
6
7
render () {
return (
<div>
<lmg src={this.props.soure} />
</div>
)
}

Exercice

  • Create a component called CountNumber to show the number of clicks and include it from Counter.
  • Set the number of clicks passing its value by props.

Redux

Following in the steps of Flux, CQRS, and Event Sourcing, Redux attempts to make state mutations predictable by imposing certain restrictions on how and when updates can happen. These restrictions are reflected in the three principles of Redux.

Motivation


The three principes of redux


Single source of truth

The state of your whole application is stored in an object tree within a single store.


State is read-only

The only way to change the state is to emit an action, an object describing what happened.


Changes are made with pure functions

To specify how the state tree is transformed by actions, you write pure reducers.


Data Flow

Redux architecture revolves around a strict unidirectional data flow.

redux-data-flow


Using redux with react.js

  • The first step is install the needed libraries:
1
npm install --save redux react-redux

Presentational and Container Components

React bindings for Redux embrace the idea of separating presentational and container components. If you’re not familiar with these terms, read about them first, and then come back. They are important, so we’ll wait!


Container Component Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'

const mapStateToProps = state => {
return {
todos: state.todos
}
}

const mapDispatchToProps = dispatch => {
return { dispatch }
}

const TodoListContainer = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)

export default TodoListContainer

Exercises

  • Create a Container for your Counter application which returns the Counter component connected to state and dispatch.

Actions

Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using store.dispatch().


An action is something like this:

1
2
3
4
{
type: ADD_TODO,
text: 'Build my first Redux app'
}

You can also define action creators in this format:

1
2
3
4
5
6
7
8
9
10
11
export const addTodo = (text) => ({
type: 'ADD_TODO',
text,
})

export function addTodo(text) {
return {
type: 'ADD_TODO',
text: text,
}
}

Actions


Exercise

  • Create an action creator to increase the number of clicks.

Reducers

Reducers specify how the application’s state changes in response to actions sent to the store. Remember that actions only describe the fact that something happened, but don’t describe how the application’s state changes.


A basic reducer seems like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

const initialState = {
todos: [],
}

function reducer(state = initialState, action = {}) {
switch (action.type) {
case 'ADD_TODO':
return {
...state,
todos: [
...state.todos,
...action.text,
]
}
default:
return state
}
}

Reducers


Exercise

  • Create a reducer to increase the number of clicks in the state

Store

The Store is the object that brings them together. The store has the following responsibilities:

  • Holds application state.
  • Allows access to state via getState().
  • Allows state to be updated via dispatch(action).
  • Registers listeners via subscribe(listener).
  • Handles unregistering of listeners via the function returned by subscribe(listener).

To create and attach the store to your application run this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// index.js
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')
)

Exercises

  • Create store with your reducer and wrap your app in a Provider with the created store.
  • Use dispatch in your Counter component to dispatch your action-creator created below.


Reactjs


Redux

Comments

⬆︎TOP