-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfreecodecamp-notes.js
1256 lines (1094 loc) · 28.4 KB
/
freecodecamp-notes.js
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
// Render JSX to the DOM
ReactDOM.render(componentToRender, targetNode);
// Render a component to the DOM
ReactDOM.render(<componentToRender />, targetNode);
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>My First React Component !</h1>
</div>
);
}
}
ReactDOM.render(<MyComponent />, document.getElementById("challenge-node"));
// =======================================
// Pass Props to a Stateless Functional Component -function components are a simpler way to write components that only contain a render method and don’t have their own state.
// Passing properties to child components
// how to pass information from a parent component
// to a child component as props or properties.
// It is standard to call this value props and when dealing with stateless functional components,
// you basically consider it as an argument to a function which returns JSX.
const CurrentDate = props => {
return (
<div>
{/* change code below this line */}
<p>The current date is: {props.date}</p>
{/* change code above this line */}
</div>
);
};
class Calendar extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h3>What date is it?</h3>
{/* change code below this line */}
<CurrentDate date={Date()} />
{/* change code above this line */}
</div>
);
}
}
// ================================
// how arrays can be passed as props
// still passing infor form a parent to a child
const List = props => {
{
/* change code below this line */
}
return <p>{props.tasks.join(", ")}</p>;
{
/* change code above this line */
}
};
class ToDo extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>To Do Lists</h1>
<h2>Today</h2>
{/* change code below this line */}
<List tasks={["walk dog", "workout"]} />
<h2>Tomorrow</h2>
<List tasks={["walk dog", "workout", "shop"]} />
{/* change code above this line */}
</div>
);
}
}
// ===============================================
// Setting default Props
const ShoppingCart = props => {
return (
<div>
<h1>Shopping Cart Component</h1>
</div>
);
};
// change code below this line
ShoppingCart.defaultProps = { items: 0 };
// ========================
// Override Default Props
const Items = props => {
return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>;
};
Items.defaultProps = {
quantity: 0
};
class ShoppingCart extends React.Component {
constructor(props) {
super(props);
}
render() {
{
/* change code below this line */
}
// Overriding here
return <Items quantity={10} />;
{
/* change code above this line */
}
}
}
// =============================
// Use PropTypes to Define the Props You Expect Passed
const Items = props => {
return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>;
};
// change code below this line
Items.propTypes = {
quantity: PropTypes.number.isRequired
};
// change code above this line
// other example
// MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }
Items.defaultProps = {
quantity: 0
};
class ShoppingCart extends React.Component {
constructor(props) {
super(props);
}
render() {
return <Items />;
}
}
// ==============================
// what if the child component that you're passing a prop to is an ES6 class component,
// rather than a stateless functional component?
// The ES6 class component uses a slightly different convention to access props.
// Anytime you refer to a class component within itself, you use the this keyword.
class ReturnTempPassword extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
{/* change code below this line */}
<p>
Your temporary password is: <strong>{this.props.tempPassword}</strong>
</p>
{/* change code above this line */}
</div>
);
}
}
class ResetPassword extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h2>Reset Password</h2>
<h3>We've generated a new temporary password for you.</h3>
<h3>Please reset this password from your account settings ASAP.</h3>
{/* change code below this line */}
<ReturnTempPassword tempPassword={"123456789"} />
{/* change code above this line */}
</div>
);
}
}
// ==================================
// Review Using Props with Stateless Functional Components
// - A stateless functional component is any function you write which accepts props and returns JSX.
// - A stateless component, on the other hand, is a class that extends React.Component, but does not use internal state
// - Finally, a stateful component (React component) is a class component that does maintain its own internal state.
class CampSite extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Camper name={"CamperBot"} />
</div>
);
}
}
// change code below this line
const Camper = props => {
return (
<div>
<h1>Camper Component</h1>
<p>{props.name}</p>
</div>
);
};
Camper.defaultProps = { name: "CamperBot" };
Camper.propTypes = {
name: PropTypes.string.isRequired
};
// ===============================
// Create a Stateful Component
// State consists of any data your application needs to know about, that can change over time.
// You want your apps to respond to state changes and present an updated UI when necessary.
class StatefulComponent extends React.Component {
constructor(props) {
super(props);
// initialize state here
this.state = {
name: "Name"
};
}
render() {
return (
<div>
<h1>{this.state.name}</h1>
</div>
);
}
}
// ===========================
// Render State in the User Interface
// If you want to access a state value within the return of the render method,
// you have to enclose the value in curly braces.
// State is one of the most powerful features of components in React. It allows you to track important data in your app and render a UI in response to changes in this data.
// State is encapsualated to the component it is initialized in
// Code as above
// ===========================
// Render State in the User Interface Another Way
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "freeCodeCamp"
};
}
render() {
// change code below this line
const name = this.name;
// change code above this line
return (
<div>
{/* change code below this line */}
<h1>{name}</h1>
{/* change code above this line */}
</div>
);
}
}
// ====================================
// Change a components state with setState
// Set State with this.setState
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "Initial State"
};
this.handleClick = this.handleClick.bind(this);
// explicitly bind this in the constructor so this
// becomes bound to the class methods when the component is initialized
// when you call a function like this.setState() within your class method,
// this refers to the class and will not be undefined.
}
handleClick() {
// change code below this line
this.setState({
name: "React Rocks!"
});
// change code above this line
}
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
<h1>{this.state.name}</h1>
</div>
);
}
}
// ===========================
// Bind 'this' to a Class Method
// There are a few ways to allow your class methods to access 'this'
// - One common way is to explicitly bind this in the constructor so this
// becomes bound to the class methods when the component is initialized
// e.g. this.handleClick = this.handleClick.bind(this)
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
text: "Hello"
};
// change code below this line
this.handleClick = this.handleClick.bind(this);
// change code above this line
}
handleClick() {
this.setState({
text: "You clicked!"
});
}
render() {
return (
<div>
{/* change code below this line */}
<button onClick={this.handleClick}>Click Me</button>
{/* change code above this line */}
<h1>{this.state.text}</h1>
</div>
);
}
}
// =============================
// Use State to Toggle an Element
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
visibility: false
};
// change code below this line
this.toggleVisibility = this.toggleVisibility.bind(this);
// change code above this line
}
// change code below this line
toggleVisibility() {
this.setState(state => ({
visibility: !state.visibility
}));
}
// change code above this line
render() {
if (this.state.visibility) {
return (
<div>
<button onClick={this.toggleVisibility}>Click Me</button>
<h1>Now you see me!</h1>
</div>
);
} else {
return (
<div>
<button onClick={this.toggleVisibility}>Click Me</button>
</div>
);
}
}
}
// =======================================
// Write a Simple Counter
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
this.reset = this.reset.bind(this);
}
reset() {
this.setState({
count: 0
});
}
increment() {
this.setState(state => ({
count: state.count + 1
}));
}
decrement() {
this.setState(state => ({
count: state.count - 1
}));
}
render() {
return (
<div>
<button className='inc' onClick={this.increment}>Increment!</button>
<button className='dec' onClick={this.decrement}>Decrement!</button>
<button className='reset' onClick={this.reset}>Reset</button>
<h1>Current Count: {this.state.count}</h1>
</div>
);
}
};
// ===================================
// Create a Controlled Input
class ControlledInput extends React.Component {
constructor(props) {
super(props);
this.state = {
input: ''
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
input: event.target.value
});
}
render() {
return (
<div>
<input
value={this.state.input}
onChange={this.handleChange} />
<h4>Controlled Input:</h4>
<p>{this.state.input}</p>
</div>
);
}
};
// When you type in the input box, that text is processed by the handleChange()
// method, set as the input property in the local state, and rendered as the
// value in the input box on the page.
// ======================================
// Create a Controlled Form
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
submit: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
input: event.target.value
});
}
handleSubmit(event) {
// change code below this line
event.preventDefault()
this.setState({
submit: this.state.input
});
// change code above this line
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
{ /* change code below this line */ }
<input
value={this.state.input}
onChange={this.handleChange} />
{ /* change code above this line */ }
<button type='submit'>Submit!</button>
</form>
{ /* change code below this line */ }
<h1>{this.state.submit}</h1>
{ /* change code above this line */ }
</div>
);
}
};
// ================================
// Pass State as Props to Child Components
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'CamperBot'
}
}
render() {
return (
<div>
<Navbar name={this.state.name}/>
</div>
);
}
};
class Navbar extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>Hello, my name is: {this.props.name}</h1>
</div>
);
}
};
// ===============
// Pass a Callback as Props
// You can pass state as props to child components, but you're not limited to passing data. You can also pass handler functions or any method that's
// defined on a React component to a child component.
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
inputValue: event.target.value
});
}
render() {
return (
<div>
<GetInput
input={this.state.inputValue}
handleChange={this.handleChange}/>
<RenderInput
input={this.state.inputValue}/>
</div>
);
}
};
class GetInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h3>Get Input:</h3>
<input
value={this.props.input}
onChange={this.props.handleChange}/>
</div>
);
}
};
class RenderInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h3>Input Render:</h3>
<p>{this.props.input}</p>
</div>
);
}
};
// ===================================
// Use the Lifecycle Method componentWillMount
componentWillMount()
// The componentWillMount() method is called before the render() method
// when a component is being mounted to the DOM.
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
// change code below this line
console.log('hi!')
// change code above this line
}
render() {
return <div />
}
};
componentDidMount()
// The best practice with React is to place API calls or any calls to your server in the
// lifecycle method componentDidMount(). This method is called after a component is mounted to the DOM
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
activeUsers: null
};
}
componentDidMount() {
setTimeout( () => {
this.setState({
activeUsers: 1273
});
}, 2500);
}
render() {
return (
<div>
<h1>Active Users: { this.state.activeUsers }</h1>
</div>
);
}
};
// Add Event Listeners
// The componentDidMount() method is also the best
// place to attach any event listeners you need to add for specific functionality.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
message: ''
};
this.handleEnter = this.handleEnter.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
// change code below this line
componentDidMount() {
document.addEventListener('keydown', this.handleKeyPress)
}
componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeyPress)
}
// change code above this line
handleEnter() {
this.setState({
message: this.state.message + 'You pressed the enter key! '
});
}
handleKeyPress(event) {
if (event.keyCode === 13) {
this.handleEnter();
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
);
}
};
// =========================================
// Optimize Re-Renders with shouldComponentUpdate
class OnlyEvens extends React.Component {
constructor(props) {
super(props);
}
shouldComponentUpdate(nextProps, nextState) {
console.log('Should I update?');
// change code below this line
return nextProps.value % 2 === 0;
// change code above this line
}
componentDidUpdate() {
console.log('Component re-rendered.');
}
render() {
return <h1>{this.props.value}</h1>
}
};
class Controller extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 0
};
this.addValue = this.addValue.bind(this);
}
addValue() {
this.setState({
value: this.state.value + 1
});
}
render() {
return (
<div>
<button onClick={this.addValue}>Add</button>
<OnlyEvens value={this.state.value}/>
</div>
);
}
};
// =============================
// Inline styles
class Colorful extends React.Component {
render() {
return (
<div style={{color: 'red', fontSize: 72}}>Big Red</div>
);
}
};
// ===================
// Add Inline Styles in React
// const styles =
const styles = {
color: "purple",
fontSize: 40,
border: "2px solid purple"
};
// change code above this line
class Colorful extends React.Component {
render() {
// change code below this line
return (
<div style={styles}>Style Me!</div>
// change code above this line
);
}
};
// =========================
// Use Advanced JavaScript in React Render Method
const inputStyle = {
width: 235,
margin: 5
}
class MagicEightBall extends React.Component {
constructor(props) {
super(props);
this.state = {
userInput: '',
randomIndex: ''
}
this.ask = this.ask.bind(this);
this.handleChange = this.handleChange.bind(this);
}
ask() {
if (this.state.userInput) {
this.setState({
randomIndex: Math.floor(Math.random() * 20),
userInput: ''
});
}
}
handleChange(event) {
this.setState({
userInput: event.target.value
});
}
render() {
const possibleAnswers = [
'It is certain',
'It is decidedly so',
'Without a doubt',
'Yes, definitely',
'You may rely on it',
'As I see it, yes',
'Outlook good',
'Yes',
'Signs point to yes',
'Reply hazy try again',
'Ask again later',
'Better not tell you now',
'Cannot predict now',
'Concentrate and ask again',
'Don\'t count on it',
'My reply is no',
'My sources say no',
'Most likely',
'Outlook not so good',
'Very doubtful'
];
const answer = possibleAnswers[this.state.randomIndex];
// advanced JS is here before the return method
return (
<div>
<input
type="text"
value={this.state.userInput}
onChange={this.handleChange}
style={inputStyle} /><br />
<button onClick={this.ask}>
Ask the Magic Eight Ball!
</button><br />
<h3>Answer:</h3>
<p>
{ /* change code below this line */ }
{answer}
{ /* change code above this line */ }
</p>
</div>
);
}
};
// ===============================================
// Render with an If-Else Condition
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
display: true
}
this.toggleDisplay = this.toggleDisplay.bind(this);
}
toggleDisplay() {
this.setState({
display: !this.state.display
});
}
render() {
// change code below this line
if (this.state.display === true) {
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
<h1>Displayed!</h1>
</div>
);
} else {
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
</div>
);
}
}
};
// ==================================================
// Use && for a More Concise Conditional
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
display: true
}
this.toggleDisplay = this.toggleDisplay.bind(this);
}
toggleDisplay() {
this.setState(state => ({
display: !state.display
}));
}
render() {
// change code below this line
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
{this.state.display && <h1>Displayed!</h1>}
</div>
);
}
};
// ================================================
// Use a Ternary Expression for Conditional Rendering
const inputStyle = {
width: 235,
margin: 5
}
class CheckUserAge extends React.Component {
constructor(props) {
super(props);
// change code below this line
this.state = {
input: '',
userAge: ''
}
// change code above this line
this.submit = this.submit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({
input: e.target.value,
userAge: ''
});
}
submit() {
this.setState(state => ({
userAge: state.input
}));
}
render() {
const buttonOne = <button onClick={this.submit}>Submit</button>;
const buttonTwo = <button>You May Enter</button>;
const buttonThree = <button>You Shall Not Pass</button>;
return (
<div>
<h3>Enter Your Age to Continue</h3>
<input
style={inputStyle}
type="number"
value={this.state.input}
onChange={this.handleChange} /><br />
{
this.state.userAge === '' ?
buttonOne :
this.state.userAge >= 18 ?
buttonTwo :
buttonThree
}
</div>
);
}
};
// =================================================
// Render Conditionally from Props
class Results extends React.Component {