-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathreact.js
More file actions
597 lines (523 loc) · 15.5 KB
/
react.js
File metadata and controls
597 lines (523 loc) · 15.5 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
// REACT - Javascript Library - by Richard Rembert
/**/
// REACT FRAMEWORKS
// create-react-app -> 1st party; simple and basic; it is opinionated; many dependencies that could be useless
// next.js -> ssr or ssg; very fast; integrates best with Vercel hosting which costs
// gatsby -> very fast; plugins and themes available; hard to migrate; official gatsby hosting costs
// blitz -> not very established; good doc but not for migration; fast even with API query; needs a server (except on Vercel)
// redwood -> not very established; JAM stack; tricky migration; deploy everywhere; meant to be serverless
// remix -> very recent
// SETUP DEV
// start a new react project from scratch -> https://jscomplete.com/learn/1rd-reactful
cd projectFolder
// create package.json
npm init -y
// express to run node server
npm i express
// install react & react-dom
npm i react react-dom
// install webpack, a module bundler
npm i webpack webpack-cli
// install babel
npm i babel-loader @babel/core @babel/node @babel/preset-env @babel/preset-react
// dev dependencies
// nodemon or alternative to change server code without restarting node
npm i -D nodemon
// eslint -> add a .eslintrc.json file
npm i -D eslint babel-eslint eslint-plugin-react eslint-plugin-react-hooks
/* eslint-config-prettier eslint-config-airbnb eslint-plugin-cypress eslint-plugin-import eslint-plugin-jest eslint-plugin-jsx-a11y eslint-plugin-prettier */
// jest for testing
npm i -D jest babel-jest react-test-renderer
// start a new react project with a builder
create-react-app project-name
create-react-app project-name --template typescript // to have typescript set up
npm start
// very useful to install react devtool
// package.json
{
"name": "ps-redux",
"description": "React and Redux Pluralsight course by Cory House",
"scripts": {
"start": "webpack serve --config webpack.config.dev.js --port 3000"
},
"dependencies": {
"bootstrap": "5.0.2",
"immer": "9.0.5",
"prop-types": "15.7.2",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-redux": "7.2.4",
"react-router-dom": "5.2.0",
"react-toastify": "7.0.4",
"redux": "4.1.0",
"redux-thunk": "2.3.0",
"reselect": "4.0.0"
},
"devDependencies": {
"@babel/core": "7.14.6",
"@testing-library/react": "^12.0.0",
"@wojtekmaj/enzyme-adapter-react-17": "^0.6.2",
"babel-eslint": "10.1.0",
"babel-loader": "8.2.2",
"babel-preset-react-app": "10.0.0",
"css-loader": "5.2.6",
"cssnano": "5.0.6",
"enzyme": "3.11.0",
"eslint": "7.30.0",
"eslint-loader": "4.0.2",
"eslint-plugin-import": "2.23.4",
"eslint-plugin-react": "7.24.0",
"fetch-mock": "9.11.0",
"html-webpack-plugin": "5.3.2",
"http-server": "0.12.3",
"jest": "27.0.6",
"json-server": "0.16.3",
"mini-css-extract-plugin": "2.1.0",
"node-fetch": "^2.6.1",
"npm-run-all": "4.1.5",
"postcss": "^8.3.5",
"postcss-loader": "6.1.1",
"react-test-renderer": "17.0.2",
"redux-immutable-state-invariant": "2.1.0",
"redux-mock-store": "1.5.4",
"rimraf": "3.0.2",
"style-loader": "3.0.0",
"webpack": "5.44.0",
"webpack-bundle-analyzer": "4.4.2",
"webpack-cli": "4.9.0",
"webpack-dev-server": "3.11.2"
},
"engines": {
"node": ">=8"
},
"babel": {
"presets": [
"babel-preset-react-app"
]
},
"eslintConfig": {
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:import/errors",
"plugin:import/warnings"
],
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"env": {
"browser": true,
"node": true,
"es6": true,
"jest": true
},
"rules": {
"no-debugger": "off",
"no-console": "off",
"no-unused-vars": "warn",
"react/prop-types": "warn"
},
"settings": {
"react": {
"version": "detect"
}
},
"root": true
}
}
// webpack.config.dev.js
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
process.env.NODE_ENV = 'development';
module.exports = {
mode: 'development',
target: 'web',
devtool: 'cheap-module-source-map',
entry: './src/index',
output: {
path: path.resolve(__dirname, 'build'),
publicPath: '/',
filename: 'bundle.js',
},
devServer: {
stats: 'minimal',
overlay: true,
historyApiFallback: true,
disableHostCheck: true,
headers: { 'Access-Control-Allow-Oriigin': '*' },
https: false,
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html',
favicon: 'src/favicon.ico',
}),
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader'],
},
{
test: /(\.css)$/,
use: ['style-loader', 'css-loader'],
},
],
},
};
// SET UP PRODUCTION BUILD
// the goal is to end up with a build folder composed of index.html, bundle.js and styles.css
// package.json
{
"name": "ps-redux",
"description": "React and Redux Pluralsight course by Cory House",
"scripts": {
"start": "run-p start:dev start:api",
"start:dev": "webpack serve --config webpack.config.dev.js --port 3000",
"prestart:api": "node tools/createMockDb.js",
"start:api": "node tools/apiServer.js",
"test": "jest --watchAll",
"test:ci": "jest",
"clean:build": "rimraf ./build && mkdir build",
"prebuild": "run-p clean:build test:ci",
"build": "webpack --config webpack.config.prod.js",
"postbuild": "run-p start:api serve:build",
"serve:build": "http-server ./build"
},
"jest": {
"setupFiles": [
"./tools/testSetup.js"
],
"testEnvironment": "jsdom",
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/tools/fileMock.js",
"\\.(css|less)$": "<rootDir>/tools/styleMock.js"
}
},
"dependencies": {
"bootstrap": "5.0.2",
"immer": "9.0.5",
"prop-types": "15.7.2",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-redux": "7.2.4",
"react-router-dom": "5.2.0",
"react-toastify": "7.0.4",
"redux": "4.1.0",
"redux-thunk": "2.3.0",
"reselect": "4.0.0"
},
"devDependencies": {
"@babel/core": "7.14.6",
"@testing-library/react": "^12.0.0",
"@wojtekmaj/enzyme-adapter-react-17": "^0.6.2",
"babel-eslint": "10.1.0",
"babel-loader": "8.2.2",
"babel-preset-react-app": "10.0.0",
"css-loader": "5.2.6",
"cssnano": "5.0.6",
"enzyme": "3.11.0",
"eslint": "7.30.0",
"eslint-loader": "4.0.2",
"eslint-plugin-import": "2.23.4",
"eslint-plugin-react": "7.24.0",
"fetch-mock": "9.11.0",
"html-webpack-plugin": "5.3.2",
"http-server": "0.12.3",
"jest": "27.0.6",
"json-server": "0.16.3",
"mini-css-extract-plugin": "2.1.0",
"node-fetch": "^2.6.1",
"npm-run-all": "4.1.5",
"postcss": "^8.3.5",
"postcss-loader": "6.1.1",
"react-test-renderer": "17.0.2",
"redux-immutable-state-invariant": "2.1.0",
"redux-mock-store": "1.5.4",
"rimraf": "3.0.2",
"style-loader": "3.0.0",
"webpack": "5.44.0",
"webpack-bundle-analyzer": "4.4.2",
"webpack-cli": "4.9.0",
"webpack-dev-server": "3.11.2"
},
"engines": {
"node": ">=8"
},
"babel": {
"presets": [
"babel-preset-react-app"
]
},
"eslintConfig": {
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:import/errors",
"plugin:import/warnings"
],
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"env": {
"browser": true,
"node": true,
"es6": true,
"jest": true
},
"rules": {
"no-debugger": "off",
"no-console": "off",
"no-unused-vars": "warn",
"react/prop-types": "warn"
},
"settings": {
"react": {
"version": "detect"
}
},
"root": true
}
}
// webpack.config.prod.js
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpackBundleAnalyzer = require('webpack-bundle-analyzer');
process.env.NODE_ENV = 'production';
module.exports = {
mode: 'production',
target: 'web',
devtool: 'source-map',
entry: './src/index',
output: {
path: path.resolve(__dirname, 'build'),
publicPath: '/',
filename: 'bundle.js',
},
plugins: [
new webpackBundleAnalyzer.BundleAnalyzerPlugin({ analyzerMode: 'static' }),
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.API_URL': JSON.stringify('http://localhost:3001'),
}),
new HtmlWebpackPlugin({
template: 'src/index.html',
favicon: 'src/favicon.ico',
minify: {
// see https://github.com/kangax/html-minifier#options-quick-reference
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader'],
},
{
test: /(\.css)$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true,
},
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [() => [require('cssnano')]],
},
sourceMap: true,
},
},
],
},
],
},
};
// BASICS
// use those import everytime! They are needed in all examples
import React from "react";
import ReactDOM from "react-dom";
// write JSX elements just as HTML
const h1 = <h1>React JS</h1>;
// define element attribute just as in HTML
const a = <a href="#0">What a link!</a>;
// multiline element are possible using parenthesis ()
const ah1 = (
<a href="#0">
<h1>
What a big link!
</h1>
</a>
);
// a JSX expression must have exactly one outermost element
// good habit is to have a <div>, or <> (<React.Fragment>, <Fragment>) wrapping everything
const blog = (
<div>
<h1>Main title</h1>
<p>Subtitle</p>
</div>
);
// render your HTML; first argument is the JSX element and the second points to the HTML where it will be rendered
// -> <div id="app"></div>
ReactDOM.render(<h1>Hello world</h1>, document.getElementById("app"));
// you can use variable of course
const myElt = <h1>Render me!</h1>;
ReactDOM.render(myElt, document.getElementById("app"));
// or create it without JSX
const myElt = React.createElement("h1", null, "Hello world");
ReactDOM.render(myElt, document.getElementById("app"));
// class property is special, contrary to HTML, JSX need it to be called className
const myDiv = <div className="big"></div>;
// self closing tags as well, they NEED the back slash
const myImg = <img src="img.jpg" />;
const myBr = <br />;
// javascript into JSX thanks to curly braces {}
const text = "The result of 2 + 3 is:";
const myJS = <p>{text + " " + 2 + 3}</p>;
// you can have comments that way
const myCom = (
<div>
<h1>Comment</h1>
{/* here is a commented text */}
</div>
);
// create event listeners
function myFunc() {
alert("Click on this image");
}
<img onClick={myFunc} />
// if else are not possibile inside JSX --> use ternary operator
const isTrue = <p>{1 === 1 ? "true" : "false"}</p>;
// JSX conditionals; will render the HTML or not based on the left of the logical operator
const showParagraph = true;
const myDiv = (
<div>{showParagraph && <p>I'm rendered because the const is true</p>}</div>
);
const hideParagraph = false;
const myDiv = (
<div>{hideParagraph || <p>I'm rendered because the const is false</p>}</div>
);
// map method and JSX; React understand it needs to make a list out of the array
// use key attribute to make list item identifiable! makte each key unique and avoid index!!
const numbers = ["one", "two", "three"];
const list = numbers.map((number, i) => <li key={"number_"+i}>{number}</li>);
ReactDOM.render(<ul>{list}</ul>, document.getElementById("app"));
// filter helps with filtering maps
const numbers = [
{n: "one", ok: true},
{n: "twoo", ok: false},
{n: "three", ok: true}
];
const list = numbers.filter(number => number.ok).map((numberFiltered, i) => <li key={"number_"+i}>{numberFiltered.n}</li>);
ReactDOM.render(<ul>{list}</ul>, document.getElementById("app"));
// COMPONENTS
// React Component
class MyComponentClass extends React.Component {
render() {
return <h1>Hello world</h1>;
}
};
ReactDOM.render(<MyComponentClass />, document.getElementById('app'));
// React Component multiline
class QuoteMaker extends React.Component {
render() {
return (
<blockquote>
<p>The world is full of objects, more or less interesting; I do not wish to add any more.</p>
<cite>Douglas Huebler</cite>
</blockquote>
);
}
};
ReactDOM.render(<QuoteMaker />, document.getElementById('app'));
// React Component with variables
const owl = {
title: 'Excellent Owl',
src: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-owl.jpg'
};
class Owl extends React.Component {
render() {
return (
<div>
<h1>{owl.title}</h1>
<img src={owl.src} alt={owl.title} />
</div>
);
}
}
ReactDOM.render(<Owl />, document.getElementById('app'));
// React Component render with logic
class Random extends React.Component {
render() {
const n = Math.floor(Math.random() * 10 + 1);
return <h1>The number is {n}!</h1>;
}
}
ReactDOM.render(<Random />, document.getElementById('app'));
// conditionals in components
const fiftyFifty = Math.random() < 0.5;
class TonightsPlan extends React.Component {
render() {
if (fiftyFifty) {
return <h1>Tonight I'm going out WOOO</h1>;
}
else {
return <h1>Tonight I'm going to bed WOOO</h1>;
}
}
}
ReactDOM.render(<TonightsPlan />, document.getElementById('app'));
// Components and this
class MyName extends React.Component {
get name() {
return 'Einstein';
}
render() {
return <h1>My name is {this.name}.</h1>;
}
}
ReactDOM.render(<MyName />, document.getElementById('app'));
// Event listener in Component
class Button extends React.Component {
scream() {
alert('AAAAAAAAHHH!!!!!');
}
render() {
return <button onClick={this.scream}>AAAAAH!</button>;
}
}
ReactDOM.render(<Button />, document.getElementById('app'));