-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReactNotes.txt
More file actions
1157 lines (1086 loc) · 43.6 KB
/
Copy pathReactNotes.txt
File metadata and controls
1157 lines (1086 loc) · 43.6 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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
GENERAL NOTES
-------------------------------------------
-------------------------------------------
-------------------------------------------
Lesson 2
React is a Javascript Library for building user interfaces.
Adding the right version of react to your site
Currently, there seems to be a bug if you add React as shown in the next video.
To fix it, replace the automatically added import paths (you'll see what I mean) with these:
https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js
https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js
This should fix. And don't worry about the React version, the entire rest of the course uses 16+ :)
codepen.io
create new pen
Use Babel as a pre-processor
add both react, react-dom to use react
write in the format
function Person (props) {
return (
<div className="person">
<h1>{props.name}</h1>
<p>Your Age: {props.age}</p>
</div>
);
}
var app = (
<div>
<Person name="Max" age="28" />
<Person name="Manu" age="31" />
</div>
);
ReactDOM.render(app,
document.querySelector('#app'));
Why react?
UI State is difficult to handle with vanilla JS
Have to manually target elements in the dom when using queryselector or jquery etc
complex apps where you add/remove elements, this becomes very cumbersome
Makes this a non issue
Focus more on business logic and not error cases
Huge ecosystem, active community and high performance
React Alternatives
Angular
Vue.js
Amber
Useful links
You shouldn't need it right now - but in case you ever want to dive in, here's the official React documenation: https://reactjs.org/
Had issues with the Codepen demo? Here's the finished source code: https://codepen.io/anon/pen/MELQaQ
Next-Gen JS
let and const
different ways of creating variables
var
const
never changes
constant value
let
variable values
value that changes
jsbin.com
another web editor that lets you input some js and see some output
Arrow functions
different syntax for creating js functions
normal function
function myFunc() {
...
}
arrow syntax
const myFnc - () => {
...
}
no more issues with the "this" keyword
Always keeps its context and doesn't ever change at runtime.
Exports and Imports (Modules)
can import content from another file
person.js
const person = {
name: 'Max'
};
export default person
utility.js
export const clean = () => {...}
export const baseData = 10;
app.js
import person from './person.js'
imports defaul and ONLY export of the file name in the receiving file is up to you
import prs from './person.js'
imports default and ONLY export of the file name in the receiving file is up to you
import { baseData } from './utility.js'
need to use curly braces and specify the exact name of the thing that we want to pull
import { clean } from './utility.js'
need to use curly braces and specify the exact name of the thing that we want to pull
import { baseData, clean } from './utility.js'
variations
default export
import { clean as cln } from './utility.js'
import * as bundled from './utility.js'
bundled.baseData
bundled.clean
Classes
inheritance
when using inheritance
class Human {
constructor(){
this.gender = 'male'
}
printGender(){
console.log(this.gender);
}
}
class Person extends Human {
constructor() {
super(); //you must use this to initialize the parent class when using inheritance
this.name = 'Max';
}
printMyName () {
console.log(this.name);
}
}
const person = new Person();
person.printMyName();
person.printGender();
Classes, Properties, and Methods
ES6
constructor() {
this.propertyValue = 'value'
}
myMethod() {...}
ES7
propertyValue = 'value'
myMethod = () => {...}
Change above code to ES7
Change the Javascript dropdown in jsbin to ES6/Babel
class Human {
gender = 'male';
printGender = () => {
console.log(this.gender);
}
}
class Person extends Human {
name = 'Max';
printMyName = () => {
console.log(this.name);
}
}
const person = new Person();
person.printMyName();
person.printGender();
Spread & Rest Operators
...
depends on where you use it to determine what you call it
Spread
used to split up array elements OR object properties
const newArray = [...oldArray, 1, 2] //takes the contents of oldArray and adds 1 and 2 to it and populates that result into newArray
const newObject = {...oldObject, newProp: 5} //takes the oldObject and adds newProp to it as a key/value pair.. if it already has a newProp, our property takes precidence.
Example
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4];
console.log(newNumbers);
Rest
used to merge a list of function arguments into an array
function sortArgs(...args) {
return args.sort();
}
Example 1
const person = {
name: 'Max'
}
const newPerson = {
...person,
age: 28
}
console.log(newPerson);
Example 2
const filter = (...args) => {
return args.filter(el => el === 1);
}
console.log(filter(1,2,3));
Destructuring
easily extract single array elements or object properties and store them in variables
Array destructuring
[a, b] = ['Hello', 'Max']
console.log(a) //Hello
console.log(b) //Max
Example
const numbers = [1, 2, 3];
[num1, num2] = numbers;
[num1a, , num3] = numbers;
console.log(num1, num2);
console.log(num1a, num3);
Object destructuring
{name} = {name: 'Max', age: 28}
console.log(name) //'Max'
console.log(age) //undefined
Copying an object vs pointing to the reference
if you point to the reference, then modify the original object, the new object will get the object of the original
if you copy an object, then modify the original object, the new object will retain it's value once it was copied
Refreshing array functions
map
const numbers = [1, 2, 3];
const doubledArray = numbers.map((num) => {
return num * 2;
});
console.log(numbers);
console.log(doubledArray);
Build Workflow
Optimize Code
Use next-gen js features
Be more productive
Use Dependency Management tool (npm)
Use Bundler to bundle our code to run on all browsers (webpack)
Use compiler for next gen js (babel + pre-sets)
Use a local development server
-There is a tool for this created by React to get a base project
Create React App repo. download the repo
npm install create-react-app -g
In the folder that you want to install,
create-react-app react-complete-guide
Basic Folder structure
packages.json
general dependencies
node-modules
holds all dependencies and sub dependencies for a project
Automatically updated when you run npm install in your project folder
public folder
index.html
our single html page for our project.
where our script file gets injected
<div id="root"> where you actually mount our application
where all meta-tags are added etc
manifest.json
has some meta data defined for the application
source folder
react application
index.js
ReactDOM.render on the root which is triggered in public/index.html
Renders App and imports App from..
App.js
this is the rendered first react component
App.css
defines stylings in App.js
are not scoped to the App.js. it is a global styling.
Index.css
also applies styling globally
registerServiceWorker
pre-caches all of our script files. Leave this alone
.test.js
allows us to create tests
Understanding basic components
Typically, you render one root component, the App component
you would nest all other components your application might need
those components can be nested there as well
Your components extend component.. with a render method
Every react component HAS TO return or render some html code that displays to the screen
Export the App class with default
just means when you import the class, you get the default set up
the jsx in the js file (looks like html) is the syntactic sugar to write "html"
is equivelant to React.createElement([elementYouWantToRender], [JavascriptObject], [textForElement]);
return React.createElement('div', {className: 'App'}, React.createElement('h1', null, 'Hi, I\'m a react app'));
equals
<div className="App">
<h1>Hi, I'm a react app</h1>
</div>
JSX Restrictions
since the html is actually javascript
class can't be used
must have one root element
is laxed in a later version, but it should be considered best practice
Creating an functional component
New folder components and component file start with a capital letter by convention
can omit '.js' extensions from imports. It is added automatically
By convention object should start with upper case characters; lowercase elements are reserved for lowercase character in jsx
Functional components
also referred to as "presentational", "dumb" or "stateless" components
const cmp = () => { return <div>some JSX</div> }
using ES6 arrow functions as shown here is recommended but optional
class-based components
also referred to as "containers", "smart" or "stateful" components
class Cmp extends Component { render () { return <div>some JSX</div> } }
To pass things to you component, use props
const person = (props) => {
return <p>I'm {props.name} and I am {props.age} years old!</p>
}
for functional you can use {props.Name}
for class components use {this.props.Name}
To access what is inside the html element
<Person name="Manu" age="26">My Hobbies: Racing</Person>
use {props.children}
Managing state
is only available when extending components and is only available in class components
you should use state with care, because using it too often makes your app unpredictable and difficult to manage
the special thing about state (and props) is if it changes it tells react to update the dom
Handling Events and Methods
use "Handler" at the post-fix of you method to let the reader know that it is an event handler
in your onClick
adding onClick={this.myEventHandler()} would execute immediately (adding ()).
Dont add it if you want to do this
unless you execute it as a function
onClick={() => this.myEventHandler()}
dont use this if you don't have to because it can be inefficient. Use the bind syntax instead
https://reactjs.org/docs/events.html#supported-events
Gives a list of types of events that can be listened to from react
State
You cannot change state directly. You need to use this.setState
will merge whatever you define with the existing data. Will only update the vales that you specified
most components should not allow for changing of the application state
also known as a container
You can pass event listeners and methods in the props as well to child components
You can change the state from children by doing this and having the actual change in the container
bind
bind(this, 'Maximilian')
"this" binds this to the class that it is in
second argument is what you are going to set it to
Event Handlers
nameChangedHandler = (event) => {
this.setState({
persons: [
{ name: 'Max', age: 28 },
{ name: event.target.value, age: 29 },
{ name: 'Stephanie', age: 26 },
]});
}
This extracts the target value of the event
Adding Styling and Stylesheets
2 ways
adding a .css file to the component folder (preferred; if possible)
is not scoped to the component. It's global. So you use the classname and add that to the component
By default, no file is included into the workflow by default. You have to include it
inline styles
not global
creating a js constant with the style info in it
const style = {
backgroundColor: 'whtte',
font: 'inherit',
border: '1px solid blue',
padding: '8px'
};
Then setting the style of the element to that
<button style={style} onClick={() => this.switchNameHandler('Maximilian')}>Switch Name</button> {/*use bind if you can*/}
Userful Links
create-react-app: https://github.com/facebookincubator/create-react-app
Introducing JSX: https://reactjs.org/docs/introducing-jsx.html
Rendering Elements: https://reactjs.org/docs/rendering-elements.html
Components & Props: https://reactjs.org/docs/components-and-props.html
Listenable Events: https://reactjs.org/docs/events.html
Rendering lists and conditional content
Can conditionally render content by adding a ternary expression
wrap the conditional code block in "this.state.showPersons ? <div>...</div> : null"
Place them into a variable.
let persons = null;
if(...){ persons = (<div>blah</div>)};
Put decision points into a variable
Outputting lists
Map them to a jsx object
{this.state.persons.map((person, index) => {
return <Person
name={person.name}
age={person.age}
click={this.deletePersonHandler}/>
})}
Always update state in an immutable fashion
// const persons = this.state.persons.slice(); //OR
const persons = [...this.state.persons]; //ES6 version spread operator
persons.splice(personIndex, 1);
this.setState({
persons: persons
});
When cloning objects, use the spread operator
const person = {...this.state.persons[personIndex]};
//const person2 = Object.assign({}, this.state.persons[personIndex]);
Useful Resources and links
Conditional Rendering: https://reactjs.org/docs/conditional-rendering.html
Lists & Keys: https://reactjs.org/docs/lists-and-keys.html
Keys always have to be on the outer div of the list in a map method
Styling React Components (Deep Dive)
How to handle pseudo selectors (hover, visited,etc)
When using inline styles, you can just modify the js object for style
style.backgroundColor = 'red';
Setting class names dynamically
const classes = []; //red bold
if(this.state.persons.length <= 2){
classes.push('red');
}
if(this.state.persons.length <= 1) {
classes.push('bold');
}
<p className={classes.join(' ')}>This is really working</p>
Adding and Using Radium
Can't assign a pseudo selector or media queries in application (just in css, but this makes it globally scoped)
Can add a third party package that will allow it
npm install --save radium
import into the file that you want to use it
import Radium from 'radium';
You need to wrap your app with Radium
export default Radium(App);
This is called a higher level component. This injects extra functionality into your application/component
To use for pseudo selectors...
const style = {
backgroundColor: 'green',
color: 'white',
font: 'inherit',
border: '1px solid blue',
padding: '8px',
cursor: 'pointer',
':hover': {
backgroundColor: 'lightgreen',
color: 'black'
}
};
To re-assign to pseudo selectors...
style[':hover'] = {
backgroundColor: 'lightred',
color: 'black'
}
Media Queries
Need to wrap root application for things that are transforming the app
import Radium, {StyleRoot} from 'radium';
Then the entire div in the app root
<StyleRoot>
<div className="App">
...
</div>
</StyleRoot>
const style = {
'@media (min-width: 500px)': {
width: '450px'
}
};
Then just add to style prop as normal
<div className="Person" style={style}>
CSS Modules
Making the xxx.cs files scoped to the cooresponding js components
To do this we need to tweak the build configuration of our project
To get access to this configuration we run npm eject
**there is no way back after this has been done
Converts an "everything is managed for me" project to an "everything is managed for me except the configuration" project
Need to have all changes committed and pushed before running the eject command. it will not work otherwise
run "npm run eject" in the command window
WebPack is the tool responsible for css in folders being global
In webpack.config.dev file, add "modules: true," and "localIdentName: '[name]__[local]__[hash:base64:5]'" near the test:/\.css#/ command
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]'
}),
}
copy that configuration to webpack.config.prod
Now when we import files, it is scoped to its components
the in the class that you are using styles, change
import './App.css' to import classes from './App.css';
then it can be used as an object with the css properties able to be used as objects
.App { width: 450px; }
use like <civ className={classes.App}>
Will generate something like <div class="Post__Post__ah5_1">...</div>
When doing these changes, you have to restart the project in npm
Still a relatively new concept, you can learn more about CSS Modules
https://github.com/css-modules/css-modules
If you still want to make a style global, you can by using the below in you css file
:global .Post { ... }
For pseudo selectors:
define in the css class and apply to the sub-selector when you use things like 'button' or 'button.Red'
Media Queries
do it in css as well
More reference links
Using CSS Modules in create-react-app Projects: https://medium.com/nulogy/how-to-use-css-modules-with-create-react-app-9e44bec2b5c2
More information about CSS Modules: https://github.com/css-modules/css-modules
Debugging
always scroll up to the top of the error messages to get an idea of what happened
even if the message itself is cryptic, it should give you a line number for a place to start
Logical errors
use the chrome developer tools and dig into localhost/static/js/src to get to the file and step through
Developer tools allows you to debug the code you wrote, even though it is not the compiled version of code running in the browsers
React Developer tools. Add to chrome, then React should show up in the tab
helps tell you the current state of different elements in the app
Error Boundaries
higher order components used for handling errors a component might throw
code that might fail at runtime; show a custom error message to the user
extends Component
override componentDidCatch and set state = {hasError: false, errorMessage: ''}
handle this.hasErrors = true in the render
import it in the container component and wrap the component with the error boundary
in your component throw the error when needed
throw new Error("Something went wrong");
In development mode, you will see the error in an "Error: Something went wrong" window.
In production this wont happen. It will show what you rendered inside of your error boundary
Dont cluster your entire app in them though, only use them when it makes sense
Useful debugging links
Error Boundaries: https://reactjs.org/docs/error-boundaries.html
Chrome Devtool Debugging: https://developers.google.com/web/tools/chrome-devtools/javascript/
Components Deep Dive
A Better Project Structure
Render method should be lean and not contain too much jsx
State logic should be split up from main render logic
Shorthand for returning jsx in component
const persons = (props) => (...); //dont need "return"
const persons = (props) => props.persons.map((person, index) =>
<Person
key={person.id}
name={person.name}
age={person.age}
click={() => this.deletePersonHandler(index)}
changed={(event) => this.nameChangedHandler(event, person.id)}></Person>
);
Comparing stateful and stateless components
Stateless components
should create these functional components whenever possible
have a narrow focus and a specific responsibility
CANNOT manage state
implemented by
const xy = (props) => {...}
NO access to state
NO lifecycle hooks
Access props via "props"
props.xy
Use in all other cases than below
Stateful components (containers)
want to have as minimal of these as possible
it is super hard to track the state
root component of specific features could possibly be containers that manage state for those features
implemented by
class XY extends Component
Access to state
Access to lifecycle hooks
Access state and props via "this"
this.state.XY
this.props.XY
this "props" is available when you extend Component for free.. the same way that state is available for free
Use ONLY if you need to manage State or access to lifecycle hooks
Component Lifecycle
Can define methods in a STATEFUL component which react will execute during lifecycle phases
constuctor
componentWillMount
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
componentDidCatch
componentDidMount
componentWillMount
render
During creation, the following are executed (and in order)
constuctor is executed with the props
a default ES6 class feature
have to call super(props)
may initialize state here
SHOULD set up state
Can do this here (older way) or if all you're doing is setting up state, can do it in the initialize (recommended)
SHOULD NOT cause side effects
calling out to a web service, etc
requests that come back and edit the state
could lead to a re-render of application and cause performance issues
componentWillMount
defined by react and available because we extended react
exists for historic reasons
DO: Update state, last minute optimizations
DONT: Cause side effects
render
gives react an idea of what it should look like if it looked to real DOM and rendered.. if no change needs to be made it wont re-render. if it does it will
prepare and structure JSX
then renders each child component in the class
componentDidMount
DO: Cause side effects
DONT: Update state (triggers re-render)
Component Creation: Lifecycles in action
Lifecycle hooks are usually located at or near the top of the class
componentWillUnmount()
gets executed right before a component is removed from the DOM
Components Lifecycle - Update (triggered by parent [outside])
componentWillReceiveProps (nextProps)
DO:
Sync state to props
DONT:
cause side effects
shouldComponentUpdate(nextProps, nextState)
may cancel updating process
careful though: this could cause your DOM to be in an incorrect state
DO:
Decide whether to continue or not
DONT:
cause side effects
componentWillUpdate(nextProps, nextState)
DO:
sync state to props
could be better than doing it in componentWillReceiveProps, b/c you know the update is happening for sure
DONT:
cause side effects
render
prepare and structure your JSX code
Update Child Component Props
componentDidUpdate
DO:
cause side effects
DONT:
Update state (triggers re-render)
Component Lifecycle - Update (triggered by internal change) - only difference is that componentWillReceiveProps is missing
shouldComponentUpdate(nextProps, nextState)
may cancel updating process
careful though: this could cause your DOM to be in an incorrect state
DO:
Decide whether to continue or not
DONT:
cause side effects
componentWillUpdate(nextProps, nextState)
DO:
sync state to props
could be better than doing it in componentWillReceiveProps, b/c you know the update is happening for sure
DONT:
cause side effects
render
prepare and structure your JSX code
Update Child Component Props
componentDidUpdate
DO:
cause side effects
DONT:
Update state (triggers re-render)
Performance gains from Pure Components
React will sometimes go through all of the render stages even if no changes were actually made
React needs to look to see whether it needs to re-render
This can be a performance issue for larger applications
Don't mistake this for react re-rendering the actual DOM
shouldComponentUpdate(nextProps, nextState)
Doing a comparison of every object in the props against nextProps (or state to nextState) for equality doesn't have to be done
shouldComponentUpdate(nextProps, nextState) {
return nextProps.persons !== this.props.persons ||
nextProps.changed !== this.props.changed ||
nextProps.clicked !== this.props.clicked;
}
Instead ... you can inherit from PureComponent instead of Component b/c it has the type of above check already built in
Then this type of check will happen automatically
Should only use pure components when you know that updates are not always required
Pure components could prevent child components from updating as well
How React Updates the App and Component Tree
If a parent component only passes props/state down to child components that should only be updated when those values change, then it makes sense to have the parent component be a pure component
Understanding React's DOM Updating Strategy
render being called does NOT always render to the real DOM
It is more of a suggestion as to what the html should look like at the end
Use shouldComponentUpdate to stop unneccessary render calls
compares virtual DOMs
old virtual dom vs re-rendered virtual DOM
this comparison is faster than the real DOM
checks for differences
If they are found, it re-renders the DOM in the places that changes were detected
If none were found, the don't touch the real DOM
Higher Order Components (hoc)
normal react components that are designed to wrap other components to add functionality
If these classes only add functionality and do not return direct JSX, then they start with a lower-case character
they also wrap the export default declaration
export default withClassAlt(App);
Example of the wrapping class
import React from 'react';
const withClassAlt = (WrappedComponent, className) => {
return (props) => (
<div className={className}>
<WrappedComponent {...props} />
</div>
)
}
export default withClassAlt;
Aux
removed the need for an outer level container html element for components if it's not needed
const aux = (props) => props.children;
export default aux;
after react 16.2, this is a built in FRAGMENT
instead of using like <div> ... </div>, you can use <> ... </>
Passing unknown props
To const -> you pass these with the spread operator
<WrappedComponent {...props} />
to functions
const withClassAlt = (WrappedComponent, className) => {
return class extends Component {
render() {
return <div className={className}>
<WrappedComponent {...this.props} />
</div>
}
}
}
export default withClassAlt;
Using SetState Correctly
always update state through immutable objects
set state is executed async
you cant rely on this.state being called in the set state to be correct, if a certain state element is set in another place in your app
There is a better way
this.setState( (prevState, props) => {
return {
showPersons: !doesShow,
toggleClicked: prevState.toggleClicked + 1
}
}
This ensures that the current version of the object/variable is the latest version
Validating props
can restrict the types and values you receive for your props
there is another package for this [Does NOT work in functional components]
npm install --save prop-types
import PropTypes from 'prop-types';
below your class definition, right above your export, add
{YourObject}.propTypes = {
click: PropTypes.func,
name: PropTypes.string,
age: PropTypes.number,
changed: PropTypes.func
}
More on PropTypes
https://reactjs.org/docs/typechecking-with-proptypes.html
Using Referencing "ref"
adding a special property to your html elements that will allow access in the js methods
Only available in stateful components
<input
ref={(inp) => {this.inputElement = inp}}
type="text"
onChange={this.props.changed}
value={this.props.name} />
this.inputElement is available after render
To interact with the element then you just do
this.inputElement ...
these should be used with care.. should not be a shortcut for being lazy
usually for controlling focus or media playback. NOT for styling etc
UPDATED inn 16.3
in constructor Add
this.inputElement = React.createRef(); //inputElement is whatever you want your element to be named
on the element, you would then..
ref={this.inputElement}
to interact with the element you do..
if(this.props.position === 0){
this.inputElement.current. ...
Also adds
ref ability to mapped elements of a parent.. you can then call functions on a child
unless.. that child component is wrapped by a higher order component..
there is a fix though called a forward ref
const withClassAlt = (WrappedComponent, className) => {
const WithClassAlt = class extends Component {
render() {
return <div className={className}>
<WrappedComponent ref={this.props.forwardedRef} {...this.props} />
</div>
}
}
return React.forwardRef((props, ref) => {
return <WithClassAlt {...props} forwardedRef={ref} />
});
}
Again only need these when your component is wrapped by a higher level component
Context API (16.3)
tool for passing global state around in your app
i.e. - passing around logged in state globally
to create, in the top level component, OUTSIDE of the class at the top
export const AuthContext = React.createContext(false);
then where you want to use it, wrap in the provider, wrapping all the lower level consumer components
<AuthContext.Provider value={this.state.authenticated}>
{persons}
</AuthContext.Provider>
then in the class where you want to use, import it
import {AuthContext} from '../../../containers/App'
then call the consumer element using a method to extract the object
<AuthContext.Consumer>
{auth => auth ? <p>I am authenticated!</p> : null}
</AuthContext.Consumer>
Context API (16.6)
you have access to a static version in your child classes
you create a new component to house your authentication logic
import React from 'react'
export default React.createConext({
isAuth: false,
toggleAuth: () => {}
});
In container, import the context
import AuthContext from './auth-context'
you still need to import it into child components
import {AuthContext} from '../../../containers/App'
then within your class, you declare the static authcontext
static contextType = AuthContext;
To use inside of render
<button onClick={this.context.toggleAuth}>
{this.context.isAuth ? 'Logout' : 'Login'}
</button>
Lifecycle hooks (16.6)
should try to avoid
componentWillMount
componentWillUpdate
componentWillReceiveProps
these are discouraged because they are often used incorrectly and are not that useful
React offers 2 new ones
static getDerivedStateFromProps(nextProps, prevState)
whenever you need to bring state and props in sync
executes whenever your props are updated
state should rarely be coupled to props
getSnapshotBeforeUpdate()
gets a snapshot of the DOM right before the DOM updates
sometimes you get states when you receive new props and you want it to work with state
for example,
saving the current scroll state of the user to put them back in the previous position
The "memo" method
how we can effectively re-render our components (PureComponents)
could only do this on functional based components though
with 16.6, you can also optimize functional components
you wrap your component with
export default React.memo(cockpit);
Does not mean you have to wrap all components with the memo function
Useful links
State & Lifecycle: https://reactjs.org/docs/state-and-lifecycle.html
PropTypes: https://reactjs.org/docs/typechecking-with-proptypes.html
Higher Order Components: https://reactjs.org/docs/higher-order-components.html
Refs: https://reactjs.org/docs/refs-and-the-dom.html
Course Project
Planning a React App
1) Component Tree / Component Structure
2) Application State (Data)
3) Components vs Containers
Routing
Multiple pages in a SPA
Single Page (HTML File)
use js to render parts of different pages for different paths
Will use a router package
parses url / path
read configuration to know which paths are supported and what happens when a user visits them
render / load appropriate jsx / components
-------------------------------------------
-------------------------------------------
-------------------------------------------
HTTP EXAMPLE
-------------------------------------------
-------------------------------------------
-------------------------------------------
Site for testing out API calls and requests w/ dummy data
jsonplaceholder.typicode.com
Typically use a third party js library for handling http requests
axios can be used for this
https://github.com/axios/axios
Not something strongly connected to react, it can be installed with any js code
npm install --save axios
In your component
import axios from 'axios';
In componentDidMount
axios.get('{http address}')
Uses promises
axios.get('http://jsonplaceholder.typicode.com/posts')
.then(response => {
});
HTTP Get request
Use componentDidMount for fetching calls
Transforming data
when you fetch too much data, transform it after you get it
const posts = response.data.slice(0, 4)
posting
const post = {
title: this.state.title,
body: this.state.content,
author: this.state.author
}
axios.post("http://jsonplaceholder.typicode.com/posts", post)
.then(response => {
console.log(response);
});
axios will turn the "post" object into json data for us automatically
status 201 shows that it was successful
deleting
axios.delete("http://jsonplaceholder.typicode.com/posts/" + this.state.selectedPostId)
.then(response => {
console.log(response);
})
Interceptors
global listeners with axios
usually add these near the top level of your application. For the example we add in index.js
always need to RETURN the request/response configuration, otherwise it will never get returned to the rest of the app
To register a new interceptor
for request
axios.interceptors.request.use(request => {
console.log(request);
//Edit request config
return request;
}, error => {
console.log(error);
return Promise.reject('ERROR: ' + error);
});
for response
axios.interceptors.response.use(response => {
console.log(response);
//Edit response config
return response;
}, error => {
console.log(error);
return Promise.reject('ERROR: ' + error);
})
Common use is to add an authorization header or something like that
To remove an interceptor
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
Shorthand for returning is as follows
axios.interceptors.response.use(res => res, error => {
this.setState({
error: error
})
});
Setting default configuration for axios
If we wanted to turn axios.get('http://jsonplaceholder.typicode.com/posts') to axios.get('/posts'), we could accomplish this
Also do this near or at the top level of your application
Do this by accessing axios.defaults
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
Other things that can be set globally
axios.defaults.headers.common['Authorization'] = 'AUTH TOKEN';
//can only add data to specific request types
axios.defaults.headers.post['Content-Type'] = 'application/json';
Creating and using Axios instances
What if you wanted to use one baseURL for certain parts of your application and a different one for other parts?
You use axios instances for this
The instance will assume the default setup initially created, but override anything overriden in the new instance
Create in a few file
import axios from 'axios';
//creates an instance of axios, a copy of the axios object
const instance = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com'
});
//overriding other pieces
instance.defaults.headers.common['Authorization'] = 'AUTH TOKEN FROM INSTANCE';
export default instance;
then import it from your components
import axios from '../../axios';
Interceptors set globally will no longer work though since we are using the instance
Routing
will add links to the blog container, where we will then apply routing
Added links for the routing
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/new-post">New Post</a></li>
</ul>
</nav>
</header>
add packages
npm install --save react-router react-router-dom
-------------------------------------------
-------------------------------------------
-------------------------------------------
BURGER APP
-------------------------------------------