-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1485 lines (1232 loc) · 88.4 KB
/
index.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
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
<!DOCTYPE HTML>
<html lang="" >
<head>
<meta charset="UTF-8">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>React Best Practices - ashishkumarkc.com</title>
<meta name="keywords" content="accessibility,adding,advanced,ajax,alternative,alternatives,amd,an,and,android,angular,app,application,applications,apps,architecture,array,as,avoid,axios,backend,basic,basics,beginners,benefits,best,bind,blog,boilerplate,book,browsers,build,builder,built,button,by,call,can,carousel,cases,cdn,children,class,classes,classname,classnames,cli,code,codecademy,codes,coding,comments,community,company,compiler,component,components,composition,conditional,connect,constructor,container,contracting,controls,conventions,course,create,crm,crud,css,current,dashboard,data,database,datagrid,datatable,declaring,default,demo,deployment,designer,designers,developer,developers,development,do,docs,documentation,dom,dropdown,dummies,ebook,editor,elements,else,email,end,environment,enzyme,es6,event,eventemitter,events,example,examples,explained,export,exporting,exports,express,facebook,features,file,flexbox,flux,for,force,foreach,form,forms,framework,framework7,frameworks,from,front,frontend,function,functional,functions,generator,get,getinitialstate,getting,good,graphs,grid,guidelines,handler,handlers,header,hello,hide,host,hosting,how,html,ide,ideas,if,import,imports,impot,in,inline,input,interface,introduction,io,isomorphic,j,java,javascript,js,json,jsx,keyword,language,large,latest,learn,libraries,library,lids,lifecycle,lightbox,link,list,loader,made,methods,min,mobile,model,models,module,mount,multiple,mvc,mysql,native,navigation,navigator,need,nested,node,not,object,of,official,on,onchange,onclick,online,oop,open,over,overview,page,pass,patterns,performance,php,place,post,practice,practices,prerequisites,presentation,production,program,programmers,programming,programs,project,projects,prop,props,proptypes,provider,pure,quick,rails,react,reaction,reactions,reactive,reactjs,reactor,receive,redux,ref,refs,render,rendering,request,require,rerender,resources,responsive,rest,reusable,router,sample,scratch,script,scroll,search,security,select,server,session,set,setstate,showcase,simple,single,site,sites,slider,small,source,spa,spinner,stack,standards,start,started,starter,starting,state,stateless,step,structure,style,styling,submit,super,support,supported,switch,table,tables,tasks,test,testing,the,timer,to,toggle,training,transformer,tree,tubs,tutorial,types,ui,understand,understanding,unit,unmount,update,use,used,user,uses,using,validation,value,version,video,viewer,way,we,web,webpack,webpage,website,websites,what,where,will,wills,window,windows,with,world,wrapper" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="description" content="">
<meta name="generator" content="GitBook 3.2.3">
<link rel="stylesheet" href="gitbook/style.css">
<link rel="stylesheet" href="gitbook/gitbook-plugin-highlight/website.css">
<link rel="stylesheet" href="gitbook/gitbook-plugin-search/search.css">
<link rel="stylesheet" href="gitbook/gitbook-plugin-fontsettings/website.css">
<link rel="stylesheet" href="styles/website.css">
<meta name="HandheldFriendly" content="true"/>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="gitbook/images/apple-touch-icon-precomposed-152.png">
<link href='//www.kcak11.com/favicon.png' rel='icon' type='image/x-icon' />
</head>
<body>
<div class="book">
<div class="book-summary">
<div id="book-search-input" role="search">
<input type="text" placeholder="Type to search" />
</div>
<nav role="navigation">
<ul class="summary">
<li class="chapter active" data-level="1.1" data-path="./">
<a href="./">
Introduction
</a>
</li>
<li class="divider"></li>
<li>
<a href="https://www.gitbook.com" target="blank" class="gitbook-link">
Published with GitBook
</a>
</li>
</ul>
</nav>
</div>
<div class="book-body">
<div class="body-inner">
<div class="book-header" role="navigation">
<!-- Title -->
<h1>
<i class="fa fa-circle-o-notch fa-spin"></i>
<a href="." >Introduction</a>
</h1>
</div>
<div class="page-wrapper" tabindex="-1" role="main">
<div class="page-inner">
<div id="book-search-results">
<div class="search-noresults">
<section class="normal markdown-section">
<h1 id="react-best-practices">React Best Practices</h1>
<p>(Author <strong><a href="https://www.ashishkumarkc.com" target="_blank">K.C.Ashish Kumar</a></strong>)</p>
<p>A collection of best practice guidelines for ReactJS.
<!-- v1.0,2017-08-14 -->
<!-- toc --></p>
<h2 id="esnext">ESNext</h2>
<p>You can make use of some useful ESNext features in your React code.</p>
<h3 id="class-fields-and-static-properties">Class fields and static properties</h3>
<p>Make your React classes more readable:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyComponent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
state = { name: <span class="hljs-string">""</span> };
onChangeName = e => {
<span class="hljs-keyword">this</span>.setState({ name: e.target.value });
}
}
</code></pre>
<h3 id="component-class-skeleton">Component class skeleton</h3>
<p>A typical component class using ESNext syntax looks like this:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyComponent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
<span class="hljs-keyword">static</span> propTypes = { ... };
<span class="hljs-keyword">static</span> defaultProps = { ... };
state = { ... };
onEvent = () => { ... };
classMethod() { ... }
}
</code></pre>
<h2 id="prop-types">prop-types</h2>
<p>Always declare your props. Simply install the <code>prop-types</code> module from npm:</p>
<pre><code class="lang-bash">npm install --save prop-types
</code></pre>
<p>And then import the module into your component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> PropTypes <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
</code></pre>
<p>Using prop types ensures:</p>
<ul>
<li>Consumers of your component can see exactly what props are supported.</li>
<li>Console warning are displayed when the wrong prop type is used.</li>
<li>Props can be documented for use with <code>react-styleguidist</code>.</li>
</ul>
<h3 id="example-class-using-esnext-static-property-support">Example (class using ESNext static property support)</h3>
<p>The following component supports two props: <code>onClick</code> which is a function and <code>name</code> which is a string and is a mandatory prop.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> PropTypes <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Greeting</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
<span class="hljs-keyword">static</span> propTypes = {
onClick: PropTypes.func,
name: PropTypes.string.isRequired
};
render() {
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">h1</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.props.onClick}</span>></span>
Hello, {this.props.name}
<span class="hljs-tag"></<span class="hljs-name">h1</span>></span></span>
);
}
}
</code></pre>
<h3 id="example-stateless-functional-component">Example (stateless functional component)</h3>
<p>When using a stateless functional component you need to declare prop types on the function object itself:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> PropTypes <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">const</span> Greeting = props =>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">h1</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{props.onClick}</span>></span>
Hello,{props.name}
<span class="hljs-tag"></<span class="hljs-name">h1</span>></span></span>;
Greeting.propTypes = {
onClick: PropTypes.func,
name: PropTypes.string.isRequired
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Greeting;
</code></pre>
<h3 id="use-destructuring-to-import-specific-prop-types">Use destructuring to import specific prop types</h3>
<p>You can also use destructuring to import just the prop types you need. This can save typing, especially when using props of the same type.</p>
<p>For example, here is the above stateless functional component example rewritten:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { func, string } <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">const</span> Greeting = props =>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">h1</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{props.onClick}</span>></span>
Hello,{props.name}
<span class="hljs-tag"></<span class="hljs-name">h1</span>></span></span>;
Greeting.propTypes = {
onClick: func,
name: string.isRequired
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Greeting;
</code></pre>
<h3 id="using-object-shapes-and-arrays">Using object shapes and arrays</h3>
<p>You can also specify the <em>shape</em> of an object prop or the shape of arrays.</p>
<p>For example, the following component expects an array of objects.
Each object requires <code>id</code> and <code>name</code> string properties.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { arrayOf, shape, string } <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">const</span> Stores = ({ stores }) =>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">ul</span>></span>
{stores.map(store =>
<span class="hljs-tag"><<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{store.id}</span>></span>
{store.name}
<span class="hljs-tag"></<span class="hljs-name">li</span>></span>
)}
<span class="hljs-tag"></<span class="hljs-name">ul</span>></span></span>;
Stores.propTypes = {
stores: arrayOf(
shape({
id: string.isRequired,
name: string.isRequired
})
)
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Stores;
</code></pre>
<h3 id="custom-prop-types-sharing-your-shapes">Custom prop types: sharing your shapes</h3>
<p>You can easily share custom prop types by adding them to a file and exporting them for use in your project. For example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// customProps.js</span>
<span class="hljs-keyword">import</span> { string, shape } <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> store = shape({
id: string.isRequired,
name: string.isRequired
});
<span class="hljs-comment">// Stores.js</span>
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { arrayOf } <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">import</span> { store } <span class="hljs-keyword">from</span> <span class="hljs-string">"./customProps.js"</span>;
<span class="hljs-keyword">const</span> Stores = ({ stores }) =>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">ul</span>></span>
{stores.map(store =>
<span class="hljs-tag"><<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{store.id}</span>></span>
{store.name}
<span class="hljs-tag"></<span class="hljs-name">li</span>></span>
)}
<span class="hljs-tag"></<span class="hljs-name">ul</span>></span></span>;
Stores.propTypes = {
stores: arrayOf(stores).isRequired
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Stores;
</code></pre>
<h3 id="specifying-default-prop-values">Specifying default prop values</h3>
<p>You can also declare default values for props by declaring the <code>defaultProps</code> object on the component class or function. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> PropTypes <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Heading</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
<span class="hljs-keyword">static</span> propTypes = {
backgroundColor: PropTypes.string,
color: PropTypes.string,
children: PropTypes.node.isRequired
};
<span class="hljs-keyword">static</span> defaultProps = {
backgroundColor: <span class="hljs-string">"black"</span>,
color: <span class="hljs-string">"white"</span>
};
render() {
<span class="hljs-keyword">const</span> style = {
backgroundColor: <span class="hljs-keyword">this</span>.props.backgroundColor,
color: <span class="hljs-keyword">this</span>.props.color
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">h1</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{style}</span>></span>
{this.props.children}
<span class="hljs-tag"></<span class="hljs-name">h1</span>></span></span>
);
}
}
</code></pre>
<p>This can be especially useful for <code>func</code> props as it stops a potential crash if an optional function prop is not supplied. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { func } <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">const</span> Button = ({ onClick }) =>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"btn"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onClick}</span>></span>
Button
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>;
Button.propTypes = {
onClick: func
};
Button.defaultProps = {
onClick: () => {}
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Button;
</code></pre>
<h4 id="using-default-prop-values-in-stateless-functional-components">Using default prop values in stateless functional components</h4>
<p>Rather than declaring <code>defaultProps</code> for stateless functional components, you can use a combination of <strong>destructuring</strong> and <strong>default parameter values</strong> instead. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { string, node } <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">const</span> Heading = ({ children, backgroundColor = <span class="hljs-string">"black"</span>, color = <span class="hljs-string">"white"</span> }) => {
<span class="hljs-keyword">const</span> style = {
backgroundColor,
color
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">h1</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{style}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">h1</span>></span></span>
);
};
Heading.propTypes = {
backgroundColor: string,
color: string,
children: node.isRequired
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Heading;
</code></pre>
<h2 id="stateless-functional-components">Stateless Functional Components</h2>
<p>Stateless functional components are React components as JavaScript functions. They can be used for components that do not use any lifecycle methods other than render and do not use any state.</p>
<ul>
<li>Concerned with <em>how things look</em>.</li>
<li>AKA as <em>presentational</em> or <em>dumb</em> components.</li>
<li>Functional programming paradigm: <strong>stateless function components are pure functions of their props</strong>.</li>
<li>Props passed as the first function parameter.</li>
<li>Simply return the component JSX: the same as the class <code>render</code> method.</li>
<li>No state, no lifecycle methods.</li>
<li>Easy to test.</li>
<li>Easy to re-use/share.</li>
<li>Make no assumptions about application state or the data source.</li>
<li>Can be combined with container components (which may have state and may know about the data source).</li>
</ul>
<h3 id="example">Example</h3>
<p>A simple greeting component: it displays a name and calls a prop when clicked.</p>
<blockquote>
<p>Note that ES6 arrow functions are preferred.</p>
</blockquote>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { func, string } <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">const</span> Greeting = ({ onClick, name }) =>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">h1</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onClick}</span>></span>
Hello, {name}
<span class="hljs-tag"></<span class="hljs-name">h1</span>></span></span>;
Greeting.propTypes = {
onClick: func,
name: string.isRequired
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Greeting;
</code></pre>
<h3 id="simple-snapshot-testing">Simple snapshot testing</h3>
<p>You can quickly test a simple component like this using <strong>snapshot testing</strong>. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> renderer <span class="hljs-keyword">from</span> <span class="hljs-string">"react-test-renderer"</span>;
<span class="hljs-keyword">import</span> Greeting <span class="hljs-keyword">from</span> <span class="hljs-string">"../Greeting"</span>;
it(<span class="hljs-string">"renders"</span>, () => {
expect(renderer.create(<span class="xml"><span class="hljs-tag"><<span class="hljs-name">Greeting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"The name"</span> /></span>)).toMatchSnapshot();
});
</span></code></pre>
<h2 id="containers">Containers</h2>
<p>Containers are combinations of <em>state</em> and <em>presentational components</em>.</p>
<ul>
<li>Concerned with <em>how things work</em>.</li>
<li>Usually ES6 class components with state.</li>
<li>Render Re-usable stateless functional components.</li>
<li>Knowledge about the data source and/or the application state.</li>
<li>Commonly used with <code>react-redux</code>.</li>
<li>Often generated using <em>higher order components</em> (HOCs).</li>
</ul>
<h3 id="example">Example</h3>
<p><a href="https://codesandbox.io/s/Nx1lY23K6" target="_blank"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit Presentational and Container Components"></a></p>
<p>Here is a simple presentational component that renders a styled IP address:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { string } <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">const</span> styles = {
container: {
textAlign: <span class="hljs-string">"center"</span>
},
ip: {
fontFamily: <span class="hljs-string">"sans-serif"</span>,
fontSize: <span class="hljs-string">"20px"</span>,
fontWeight: <span class="hljs-string">"bold"</span>,
color: <span class="hljs-string">"blue"</span>
}
};
<span class="hljs-keyword">const</span> IPAddress = ({ ip }) =>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.container}</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.ip}</span>></span>
{ip}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>;
IPAddress.propTypes = {
ip: string
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> IPAddress;
</code></pre>
<p>And here is an example container for this component. The container knows about the data source (in this case how to fetch the current IP.)</p>
<p>Notice the following characteristics:</p>
<ul>
<li>It is an ES6 class.</li>
<li>It has state.</li>
<li>It is using component lifecycle (<code>componentDidMount</code>).</li>
<li>It is acting as a wrapper for the <code>IPAddress</code> component.</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> IPAddress <span class="hljs-keyword">from</span> <span class="hljs-string">"./IPAddress"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IPAddressContainer</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
state = { ip: <span class="hljs-string">""</span> };
componentDidMount() {
<span class="hljs-built_in">window</span>
.fetch(<span class="hljs-string">"https://api.ipify.org?format=json"</span>)
.then(response => response.json())
.then(response => {
<span class="hljs-keyword">this</span>.setState({ ip: response.ip });
});
}
render() {
<span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag"><<span class="hljs-name">IPAddress</span> <span class="hljs-attr">ip</span>=<span class="hljs-string">{this.state.ip}</span> /></span>;
}
}
</span></code></pre>
<h2 id="higher-order-components">Higher Order Components</h2>
<p>Higher Order Components (or HOCs) are used to transform a component into another component.</p>
<p><a href="https://codesandbox.io/s/RBxmkgl0" target="_blank"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit Higher Order Components"></a></p>
<ul>
<li>A HOC <strong>is a function that takes a component and returns a new component</strong>.</li>
<li>Made possible due to the compositional nature of React.</li>
<li>Often used to inject additional props into an existing component.</li>
<li>Useful for creating containers.</li>
<li>A popular example is the <code>react-redux</code> <code>connect</code> function.</li>
<li>Can be used to re-use code, hijack the <code>render</code> method and to manipulate existing props.</li>
</ul>
<h3 id="example-ip-address">Example: IP address</h3>
<p>The following HOC function will fetch the IP address and inject a prop called <code>ip</code> into <strong>any</strong> component. This is an example of using a <code>class</code> as the container.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">const</span> withIPAddress = Component => {
<span class="hljs-keyword">return</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
state = { ip: <span class="hljs-string">""</span> };
componentDidMount() {
<span class="hljs-built_in">window</span>
.fetch(<span class="hljs-string">"https://api.ipify.org?format=json"</span>)
.then(response => response.json())
.then(response => {
<span class="hljs-keyword">this</span>.setState({ ip: response.ip });
});
}
render() {
<span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag"><<span class="hljs-name">Component</span> <span class="hljs-attr">ip</span>=<span class="hljs-string">{this.state.ip}</span> {<span class="hljs-attr">...this.props</span>} /></span>;
}
};
};
export default withIPAddress;
</span></code></pre>
<p>Notice what's happening here: we are exporting a function that accepts a component as a parameter and returns an ES6 class.</p>
<p>To use this with an existing component we do something like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { string } <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">import</span> withIPAddress <span class="hljs-keyword">from</span> <span class="hljs-string">"./withIPAddress"</span>;
<span class="hljs-keyword">const</span> SimpleIPAddress = ({ ip, color = <span class="hljs-string">"black"</span> }) =>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color</span> }}></span>
{ip}
<span class="hljs-tag"></<span class="hljs-name">p</span>></span></span>;
SimpleIPAddress.propTypes = {
ip: string
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> withIPAddress(SimpleIPAddress);
</code></pre>
<p>We export the result of calling <code>withIPAddress</code>, passing in the component in which we want the <code>ip</code> prop injected.</p>
<h3 id="example-language">Example: language</h3>
<p>Here's another example of a HOC that injects the current browser language setting into any component as a prop called <code>language</code>. In this case we are using a stateless functional component as the container.</p>
<pre><code class="lang-js"><span class="hljs-comment">// withLanguage.js</span>
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">const</span> withLanguage = Component => props =>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">Component</span> {<span class="hljs-attr">...props</span>} <span class="hljs-attr">language</span>=<span class="hljs-string">{navigator.language}</span> /></span>;
export default withLanguage;
// MyComponent.js
import React from "react";
import { string } from "prop-types";
import withLanguage from "./withLanguage";
const MyComponent = ({ language }) =>
<span class="hljs-tag"><<span class="hljs-name">div</span>></span>
Browser language: {language}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>;
MyComponent.propTypes = {
language: string
};
export default withLanguage(MyComponent);
</span></code></pre>
<h3 id="chaining-hocs">Chaining HOCs</h3>
<p>Note that you can also chain HOCs together to create a new component that combines them all. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { string } <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;
<span class="hljs-keyword">import</span> withLanguage <span class="hljs-keyword">from</span> <span class="hljs-string">"./withLanguage"</span>;
<span class="hljs-keyword">import</span> withIPAddress <span class="hljs-keyword">from</span> <span class="hljs-string">"./withIPAddress"</span>;
<span class="hljs-keyword">const</span> MyComponent = ({ language, ip }) =>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span>></span>
Browser language: {language}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span>></span>
IP address: {ip}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>;
MyComponent.propTypes = {
language: string,
ip: string
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> withLanguage(withIPAddress(MyComponent));
</code></pre>
<h2 id="functions-as-children">Functions as Children</h2>
<p><a href="https://codesandbox.io/s/Q8DzMRVq" target="_blank"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit Functions as children"></a></p>
<p>An alternative pattern to HOCs is <strong>functions as children</strong> where you supply a function to call as the child of a container component: this is the equivalent of a <strong>render callback</strong>. Like HOCs you are decoupling your parent and child and it usually follows a similar pattern of a parent that has state you want to hide from the child.</p>
<p>This has some advantages over traditional HOCs:</p>
<ul>
<li>It does not pollute the <code>props</code> namespace. HOCs have an implicit contract they impose on the inner components which can cause prop name collisions especially when combining them with other HOCs.</li>
<li>You do not need to use a function to create the container: you use simple composition instead.</li>
<li>Developers do not need to call an HOC function to create a new wrapped component which can simplify the code: they simply export their child components as normal.</li>
</ul>
<p>In order for this to work you need to use a function as the special <code>children</code> prop and have the outer container component call this function when rendering.</p>
<p>For example, here is a component that exposes the browser language:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { func } <span class="hljs-keyword">from</span> <span class="hljs-string">'prop-types'</span>;
<span class="hljs-keyword">const</span> Language = ({ children }) =>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
{children(navigator.language)}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>;
Language.propTypes = {
children: func,
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Language;
</code></pre>
<p>The component simply treats the <code>children</code> prop as a function and calls it. It can be used like this:</p>
<pre><code class="lang-js"><Language>
{language =>
<p>
Browser language: {language}
</p>}
</Language>
</code></pre>
<p>The child node of <code><Language></code> is a function which returns the JSX to render.</p>
<p>Now let's imagine a component that calls an API and uses state to store the status, response and error.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { string, func } <span class="hljs-keyword">from</span> <span class="hljs-string">'prop-types'</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CallAPI</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
<span class="hljs-keyword">static</span> propTypes = {
api: string,
children: func,
};
state = {
isFetching: <span class="hljs-literal">false</span>,
data: {},
error: <span class="hljs-string">''</span>,
};
<span class="hljs-keyword">async</span> componentDidMount() {
<span class="hljs-keyword">this</span>.setState({ isFetching: <span class="hljs-literal">true</span> });
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-keyword">this</span>.props.api);
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
<span class="hljs-keyword">this</span>.setState({ isFetching: <span class="hljs-literal">false</span>, data });
} <span class="hljs-keyword">catch</span> ({ message }) {
<span class="hljs-keyword">this</span>.setState({ isFetching: <span class="hljs-literal">false</span>, error: message });
}
}
render() {
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
{this.props.children({ ...this.state })}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
}
</code></pre>
<p>The component makes an API call (specified with a prop) and maintains the state of the call. It renders by calling a function and passing through a copy of the state as an object.</p>
<p>It could be used like this:</p>
<pre><code class="lang-js"><CallAPI api="https://api.ipify.org?format=json">
{({ isFetching, data, error }) => {
if (isFetching) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
return <p>Data: {JSON.stringify(data)}</p>;
}}
</CallAPI>
</code></pre>
<p>And of course you can render normal components in the callback, for example:</p>
<pre><code class="lang-js"><CallAPI api=<span class="hljs-string">"https://api.ipify.org?format=json"</span>>
{
props => <span class="xml"><span class="hljs-tag"><<span class="hljs-name">MyComponent</span> {<span class="hljs-attr">...props</span>} /></span>
}
<span class="hljs-tag"></<span class="hljs-name">CallAPI</span>></span></span>
</code></pre>
<blockquote>
<p>There is a caveat to using this pattern: they cannot be optimised by React because <strong>they change on every render</strong> (a new function is declared on every render cycle). This rules out using <code>shouldComponentUpdate</code> and <code>React.PureComponent</code> which may lead to performance issues. Use this pattern wisely.</p>
</blockquote>
<h2 id="events">Events</h2>
<p>When using JavaScript DOM and <code>window</code> events we usually need <code>this</code> to point to our component instance.</p>
<p>Spot the bug in this code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BindBug</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
state = { toggled: <span class="hljs-literal">false</span> };
onClick(e) {
<span class="hljs-keyword">this</span>.setState({ toggled: !<span class="hljs-keyword">this</span>.state.toggled });
}
render() {
<span class="hljs-keyword">const</span> style = {
fontSize: <span class="hljs-string">"36px"</span>,
color: <span class="hljs-keyword">this</span>.state.toggled ? <span class="hljs-string">"white"</span> : <span class="hljs-string">"black"</span>,
backgroundColor: <span class="hljs-keyword">this</span>.state.toggled ? <span class="hljs-string">"red"</span> : <span class="hljs-string">"yellow"</span>
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{style}</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.onClick}</span>></span>
Click me
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
}
</code></pre>
<p>When you click on the <code><div></code> the <code>onClick</code> function handler is called which then tries to call <code>this.setState</code>. But the handler has not bound <code>this</code> to the component instance and it ends up as <code>null</code> which causes the code to crash.</p>
<h3 id="binding-events">Binding events</h3>
<p><a href="https://codesandbox.io/s/gJ6nymBE9" target="_blank"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit Event Binding"></a></p>
<p>To make this work we need to bind the <code>onClick</code> function to <code>this</code>. There are two ways to do this:</p>
<h4 id="esnext-property-initialize-syntax-recommended">ESNext property initialize syntax (recommended)</h4>
<p>The most readable way to do this is via an ESNext property initializer in conjunction with an arrow function. Arrow functions declared in this way are bound to <code>this</code> automatically:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BindClassMethod</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
state = { toggled: <span class="hljs-literal">false</span> };
onClick = e => {
<span class="hljs-keyword">this</span>.setState({ toggled: !<span class="hljs-keyword">this</span>.state.toggled });
};
render() {
<span class="hljs-keyword">const</span> style = {
fontSize: <span class="hljs-string">"36px"</span>,
color: <span class="hljs-keyword">this</span>.state.toggled ? <span class="hljs-string">"white"</span> : <span class="hljs-string">"black"</span>,
backgroundColor: <span class="hljs-keyword">this</span>.state.toggled ? <span class="hljs-string">"red"</span> : <span class="hljs-string">"yellow"</span>
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{style}</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.onClick}</span>></span>
Click me
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
}
</code></pre>
<p>Notice the syntax used here:</p>
<pre><code class="lang-js">handlerName = (params) => { ... }
</code></pre>
<p>This is the best option: it is less code and even though this syntax is experimental it is used widely at Facebook.</p>
<p>Here's another example: a component that uses <code>window.setInterval</code> to update a counter every second:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Timer</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
state = { counter: <span class="hljs-number">0</span> };
componentDidMount() {
<span class="hljs-keyword">this</span>.timerId = <span class="hljs-built_in">window</span>.setInterval(<span class="hljs-keyword">this</span>.onTimer, <span class="hljs-number">1000</span>);
}
componentWillUnmount() {
<span class="hljs-built_in">window</span>.clearInterval(<span class="hljs-keyword">this</span>.timerId);
}
onTimer = () => {
<span class="hljs-keyword">this</span>.setState(prevState => ({ counter: prevState.counter + <span class="hljs-number">1</span> }));
};
render() {
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">p</span>></span>
Counter: {this.state.counter}
<span class="hljs-tag"></<span class="hljs-name">p</span>></span></span>
);
}
}
</code></pre>
<p>Note the following:</p>
<ul>
<li>The timer ID is stored so it can be cleared when the component unmounts.</li>
<li>The function version of <code>setState</code> is used.</li>
</ul>
<p>Alternatively you could use an inline arrow function: this will ensure <code>this</code> has the correct context:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Timer</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
state = { counter: <span class="hljs-number">0</span> };
componentDidMount() {
<span class="hljs-keyword">this</span>.timerId = <span class="hljs-built_in">window</span>.setInterval(() => {
<span class="hljs-keyword">this</span>.setState(prevState => ({ counter: prevState.counter + <span class="hljs-number">1</span> }));
}, <span class="hljs-number">1000</span>);
}
componentWillUnmount() {
<span class="hljs-built_in">window</span>.clearInterval(<span class="hljs-keyword">this</span>.timerId);
}
render() {
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">p</span>></span>
Counter: {this.state.counter}
<span class="hljs-tag"></<span class="hljs-name">p</span>></span></span>
);
}
}
</code></pre>
<h4 id="constructor-binding">Constructor binding</h4>
<p>Another common way of binding is to add a constructor to your class and use <code>Function.prototype.bind</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BindConstructor</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
state = { toggled: <span class="hljs-literal">false</span> };
<span class="hljs-keyword">constructor</span>() {
<span class="hljs-keyword">super</span>();
<span class="hljs-keyword">this</span>.onClick = <span class="hljs-keyword">this</span>.onClick.bind(<span class="hljs-keyword">this</span>);
}
onClick(e) {
<span class="hljs-keyword">this</span>.setState({ toggled: !<span class="hljs-keyword">this</span>.state.toggled });
}
render() {
<span class="hljs-keyword">const</span> style = {
fontSize: <span class="hljs-string">"36px"</span>,
color: <span class="hljs-keyword">this</span>.state.toggled ? <span class="hljs-string">"white"</span> : <span class="hljs-string">"black"</span>,
backgroundColor: <span class="hljs-keyword">this</span>.state.toggled ? <span class="hljs-string">"red"</span> : <span class="hljs-string">"yellow"</span>
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{style}</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.onClick}</span>></span>
Click me
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
}
</code></pre>
<p>Although this method is not relying on any experimental syntax it suffers from the following issues:</p>
<ul>
<li>It requires you adding a constructor.</li>
<li>You have to remember call <code>super</code> in the constructor before doing anything else.</li>
<li>It is more code.</li>
</ul>
<h3 id="sharing-event-handlers">Sharing event handlers</h3>
<p><a href="https://codesandbox.io/s/vgAwR1Pxn" target="_blank"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit Shared Event Handlers"></a></p>
<p>Sometimes it is useful to share the share event handlers for your components and there is a simple trick to do this using the DOM <code>name</code> attribute (which is exposed as a prop for most React components):</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DetailsForm</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
state = {
name: <span class="hljs-string">""</span>,
email: <span class="hljs-string">""</span>,
phone: <span class="hljs-string">""</span>
}
onChange = e => {
<span class="hljs-keyword">this</span>.setState({
[e.target.name]: e.target.value
});
}
render() {
<span class="hljs-keyword">return</span> (
<div>
<input name="name" value={this.state.name} onChange={this.onChange} />
<input name="email" value={this.state.email} onChange={this.onChange} />
<input name="phone" value={this.state.phone} onChange={this.onChange} />
</div>
)
}
}
</code></pre>
<p>This takes advantage of the JavaScript <strong>computed property name syntax</strong> to update the state. Notice how the <code>name</code> prop for each <code><input></code> matches the corresponding state property: this allows us to share a single <code>onChange</code> handler with all three components.</p>
<blockquote>
<p>Although this looks like magic <strong>it's just JavaScript</strong>.</p>
</blockquote>
<h3 id="handling-the-enter-key-in-a-form">Handling the ENTER key in a form</h3>
<p><a href="https://codesandbox.io/s/RnpV11EV" target="_blank"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit Form ENTER key"></a></p>
<p>If you want to let users press the ENTER key to submit a form then you will need to prevent the default <code>submit</code> behaviour of a HTML form. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoginForm</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
onSubmit = e => {
<span class="hljs-comment">// Don't actually submit!</span>
e.preventDefault();
<span class="hljs-comment">// Enter key was pressed</span>
};
render() {
<span class="hljs-keyword">return</span> (
<form onSubmit={this.onSubmit}>
<input
name="username"
value={this.state.value}
onChange={this.onChange}
/>
<input
name="password"
type="password"
value={this.state.password}
onChange={this.onChange}
/>
<input type="submit" value="Login" />
</form>
);
}
}
</code></pre>
<p>This looks pretty much like a standard HTML form: the presence of the <code><input type="submit" /></code> ensures the ENTER key works but by calling <code>preventDefault</code> on the submit event you can handle it yourself without the application reloading.</p>
<h2 id="conditional-rendering">Conditional Rendering</h2>
<p>Sometimes it is useful to render components based on your props or state and there are at least five different mechanisms available to you (remember: it's just JavaScript!)</p>
<p><a href="https://codesandbox.io/s/QgoRP307" target="_blank"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit Conditional Rendering"></a></p>
<blockquote>
<p>Note that when you conditionally remove a component it <strong>will be re-mounted when you put it back</strong> which means <code>componentDidMount</code> and other lifecycle methods will be called again. So if you are, for example, fetching data when the component mounts, it will be called each time. To avoid this use some form of <code>show</code> prop and either return <code>null</code> from your <code>render</code> or use CSS to hide the content.</p>
</blockquote>
<h3 id="store-the-jsx-in-a-variable">Store the JSX in a variable</h3>
<p>You can declare a variable to hold the JSX you wish to render. If your condition is not met and an <code>undefined</code> variable is rendered, then React will simply ignore it.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> message;
<span class="hljs-keyword">if</span> (someCondition) {
message = <span class="xml"><span class="hljs-tag"><<span class="hljs-name">p</span>></span>Hello, world!<span class="hljs-tag"></<span class="hljs-name">p</span>></span></span>;
}
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Conditional rendering<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
{message}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
)
</code></pre>
<h3 id="ternaries">Ternaries</h3>
<p>You can also use a <strong>ternary</strong>. Using <code>null</code> or <code>undefined</code> is enough to stop anything being rendered:</p>
<pre><code class="lang-js"><span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Conditional rendering<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
{someCondition ? <span class="hljs-tag"><<span class="hljs-name">p</span>></span>Hello, world!<span class="hljs-tag"></<span class="hljs-name">p</span>></span> : null}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
)
</code></pre>
<h3 id="logical--operator-shortcut">Logical && operator shortcut</h3>
<p>This relies on the fact the JavaScript will stop evaluating an && condition if the preceding checks return <code>false</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Conditional rendering<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
{someCondition && <span class="hljs-tag"><<span class="hljs-name">p</span>></span>Hello, world!<span class="hljs-tag"></<span class="hljs-name">p</span>></span>}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
)
</code></pre>
<p>So if <code>someCondition</code> is <code>true</code> then your JSX is rendered, but if it's <code>false</code> then your JSX will simply not be evaluated.</p>
<p>This is a very common method to conditionally render something in React.</p>
<h3 id="return-null-from-your-render-method">Return null from your render method</h3>
<p>Another common pattern seen in some 3rd-party component libraries is to conditionally render a component based on a boolean prop. For example, you may have a prop called <code>show</code> that determines if the component should display at all: if not then your <code>render</code> method can simply return <code>null</code>.</p>
<blockquote>
<p>The advantage of this is that the component will not be mounted multiple times each time the <code>show</code> prop changes which is useful if you are fetching data, setting timers, etc. in <code>componentDidMount</code>.</p>
</blockquote>
<pre><code class="lang-js"><span class="hljs-comment">// MyComponent.js</span>
<span class="hljs-keyword">const</span> MyComponent = ({ show }) => {
<span class="hljs-keyword">if</span> (show) {
<span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag"><<span class="hljs-name">p</span>></span>Hello, world!<span class="hljs-tag"></<span class="hljs-name">p</span>></span></span>;
}
<span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
};
<span class="hljs-comment">// SomeOtherComponent.js</span>
...
return (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Conditional rendering<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"><<span class="hljs-name">MyComponent</span> <span class="hljs-attr">show</span>=<span class="hljs-string">{someCondition}</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
)
</span></code></pre>
<h3 id="hide-your-component-using-css">Hide your component using CSS</h3>
<p>A final way is to simply use CSS to hide your component. This also has the advantage of keeping your component mounted.</p>
<pre><code class="lang-js"><span class="hljs-comment">// MyComponent.js</span>
<span class="hljs-keyword">const</span> MyComponent = ({ show }) => {
<span class="hljs-keyword">const</span> style = {
display: show ? <span class="hljs-string">"block"</span> : <span class="hljs-string">"none"</span>
};
<span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag"><<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{style}</span>></span>Hello, world!<span class="hljs-tag"></<span class="hljs-name">p</span>></span></span>;
};
<span class="hljs-comment">// SomeOtherComponent.js</span>
...
return (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Conditional rendering<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"><<span class="hljs-name">MyComponent</span> <span class="hljs-attr">show</span>=<span class="hljs-string">{someCondition}</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
)
</span></code></pre>
<h2 id="arrays">Arrays</h2>
<p>When dealing with arrays of JavaScript objects you can use <code>Array.prototype.map</code> to map from array elements to React components. This is a very common pattern.</p>
<p>The following example shows a component that is rendering an array of stores by mapping each array entry to a new <code><li></code> component.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { arrayOf, shape, number, string } <span class="hljs-keyword">from</span> <span class="hljs-string">"prop-types"</span>;