-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreact-workshop-slides.html
320 lines (297 loc) · 7.53 KB
/
react-workshop-slides.html
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta charset="utf-8">
<style>
@import url(https://fonts.googleapis.com/css?family=Lato);
@import url(https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic);
body {
font-family: 'Lato';
}
h1, h2, h3 {
font-family: 'Lato';
font-weight: normal;
}
.remark-code, .remark-inline-code {
font-family: 'Ubuntu Mono';
}
</style>
</head>
<body>
<textarea id="source">
class: center, middle
# React
Jarda Šnajdr @jsnajdr
---
### Resources
- https://github.com/jsnajdr/react-workshop
- https://jsnajdr.github.io/react-workshop-slides.html
---
### Quick Tour of ES2015/2016/2017
Use `let` and `const` to declare variables. No more `var`.
```js
const API_KEY = "12345";
let i = 0;
API_KEY = "67890"; // error
i++; // ok
```
---
Use template literals to format strings.
```js
for (let i = 0; i < 10; i++) {
console.log(`Iteration number ${i}: ${2 * i + 1}`);
}
```
---
Use destructuring to access object and array fields.
```js
const state = {
data: [ "a", "b", "c" ],
sortOrder: "asc"
};
const { data, sortOrder } = state;
let [ first, second ] = data;
console.log(sortOrder, first, second); // "asc", "a", "b"
```
---
Use `for...of` to loop through arrays (and other iterable objects).
```js
const items = [
{ id: 1 },
{ id: 2 },
{ id: 3 }
];
for (let item of items) {
console.log("item id:", item.id);
}
// Destructure!
for (let { id } of items) {
console.log("item id:", id);
}
```
---
Be functional! (with arrow functions)
```js
const numbers = [ 1, 2, 3, 4, 5, 6 ];
// Transform array into another array
const squares = numbers.map(n => n ** 2);
// Filter array values with a filtering function
const evens = squares.filter(n => n % 2 === 0);
// Reduce the array into one value
const sum = evens.reduce((a, n) => a + n, 0);
```
---
Use spread operator to work with function parameters ...
```js
function compute(power, ...numbers) {
return numbers.reduce((a, n) => a + n ** power, 0);
}
compute(1, 3, 4); // 7
compute(2, 3, 4); // 25
```
... and arrays ...
```js
const additional = [ "b", "c" ];
const full = [ "a", ...additional ];
```
... and destructuring arrays ...
```js
const numbers = [ 1, 2, 3, 4, 5, 6 ];
const [ first, second, , ...others ] = numbers;
```
... and with objects, too!
```js
const props = { name: "user", value: "jarda", className: "user-field" };
const { name, value, ...rest } = props;
const nextProps = { id: "user", ...rest };
```
---
Use default values for parameters and destructured variables
```js
function sort(data, order = "asc") {
// sort the data
}
function sendRequest(url, options = {}) {
const { method = "GET" } = options;
performRequest(method, url);
}
sendRequest("http://github.com/api/commits");
sendRequest("http://github.com/api/createRepo", "POST");
```
---
Use classes instead of functions with prototypes.
```js
class CommitList extends React.Component {
// instance property
state = { loading: false, data: [] }
constructor(props) {
super(props);
// construct
}
render() {
// render
}
}
```
---
Use new smart methods on arrays and objects.
```js
const colors = [ "red", "green", "blue" ];
colors.find(c => c.length > 3);
colors.findIndex(c => c.startsWith("g"));
colors.includes("purple");
const ages = { jarda: 10, honza: 15, martin: 20 };
Object.keys(ages).map(console.log);
Object.values(ages).map(console.log);
for (const [ name, age ] of Object.entries(ages)) {
console.log(`${name} is ${age} years old`);
}
```
---
### Let's create a React app!
```bash
npm i -g create-react-app
create-react-app react-example
cd react-example
npm start
```
What's inside?
- `index.html` document with some markup
- `index.js` that imports the `App` component and renders it
- `App.js` component that defines some markup to be shown
- some CSS styles
- a template for mocha test
---
### Components and JSX
Component has a `render` method that declares what should be on the screen.
```js
class App extends React.Component {
render() {
let h = "Home";
return (
<div className="app">
Go to <a href="/">{ h.toUpperCase() }</a>
</div>
);
}
}
```
The JSX markup is the same thing as:
```js
React.createElement(
"div",
{ className: "app" },
"Go to ",
React.createElement(
"a",
{ href: "/" },
h.toUpperCase()
)
);
```
---
### React UI is declarative
Describe what should be on the screen, not how to get there.
```js
const { loading, error, commits } = this.state;
return (
<div className="App">
<button onClick={this.onClick} disabled={loading}>Load</button>
{ error && <div className="alert">{ error }</div> }
{ loading && <div className="loading">loading...</div> }
{ commits && <pre>{ JSON.stringify(commits, null, 2) }</pre> }
</div>
);
```
---
### React UI is composable
Presentational (dumb) components with no state, just props.
```js
class AppComponent extends Component {
render() {
const { loading, error, commits, onLoad } = this.props;
return (
<div className="App">
<button onClick={onLoad} disabled={loading}>Load</button>
<ErrorMessage error={error} />
<LoadingIndicator loading={loading} />
{ commits && <CommitList commits={commits} /> }
</div>
);
}
}
```
Can be just a function, too!
```js
const AppComponent = ({ loading, error, commits, onLoad }) => (
<div className="App">
<button onClick={onLoad} disabled={loading}>Load</button>
<ErrorMessage error={error} />
<LoadingIndicator loading={loading} />
{ commits && <CommitList commits={commits} /> }
</div>
);
```
---
### Unidirectional flow of data and actions
<div style="text-align:center"><img src="state-chart.png"/></div>
Component is a function of type State => UI (Map operation)
State update is a function of type (State, Action) => State (Reduce operation)
---
### Redux - a simple state management library
- state is stored in a Redux store
- state is the single source of truth
- state can be changed only by dispatching an action
- reducer is a pure function of state and action and produces a new state
```js
function reducer(state, action) {
return newState;
}
let store = createStore(reducer, initialState);
store.dispatch(action);
```
- clients can read the (immutable) state
```js
let state = store.getState();
```
- clients can subscribe to store updates
```js
let sub = store.subscribe(state => { ... });
```
---
### `react-redux`
`Provider` is a wrapper component to provide context to children
```js
const App = () => (
<Provider store={store}>
<ConnectedToolbar />
<ConnectedList />
</Provider>
);
```
Decorator (HOC) `connect(mapStateToProps, mapDispatchToProps)(Component)`
```js
export ConnectedComponent = connect(
state => ({
isLoading: state.commits.isLoading,
isEmpty: state.commits.list.length === 0,
commits: sortAndFilterCommits(state.commits),
}),
dispatch => ({
reload: () => dispatch(reloadAction()),
sort: (order) => dispatch(sortAction(order)),
})
)(Component);
```
---
Learn more:
- https://facebook.github.io/react/ (React)
- http://redux.js.org/ (Redux)
- https://leanpub.com/understandinges6 (ES6)
- http://www.2ality.com/ (ES6 and beyond)
</textarea>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script>remark.create();</script>
</body>
</html>