forked from sanjaysamantra1/react_notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReact Notes.txt
2542 lines (1902 loc) · 90.7 KB
/
React Notes.txt
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
Syllabus
========
-ReactJs features (VirtualDOM , ReConciliation)
-Local Environemnt Setup
-Create-react-app
-JSX
-Class Components
-Functional Components
-React Object - Fragment
-Component Styling
-Conditional rendering
-Lists & keys
-Props : de-structuring,requiring props, proptypes,default props
-State :
-Pure Component
-Memo Component
-HigherOrder Component
-Events : Synthetic Event
-Lifecycle Hooks
-Form
-Http - Axios
-Interceptors
-Routing
-REDUX (State Management)
-Unit Testing (JEST)
-EsLint
React Local Setup
=================
1. download Nodejs and install
https://nodejs.org/en/download/
2. check if nodejs is installed? (open cmd and run the below command)
node -v
3. check if NPM is installed? (NPM-Node Package Manager)
npm -v
4. go to the folder where you want to create project(d:/sanjay/react)& run the below command
npx create-react-app project1 (npx-node package executer)
5. go to the created project folder(project1) and start your React application
cd project1
npm start
6. A new browser window will pop up with your newly created React App!
open a browser tab and type 'http://localhost:3000/' if browser doesn't open automatically.
React Project with Typescript
=============================
-Create React App supports TypeScript out of the box.
-To create a new project with TypeScript support, run the below command
npx create-react-app my-app --template typescript
-To add TypeScript to an existing Create-React-App project, install the below things
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
create-react-app
================
-It is a React application boilerplate generator created by Facebook.
-This CLI tool installs React,ReactDOM & other libraries required for a react project.
-It provides a development environment configured for ease-of-use with minimal setup.
-It creates a frontend build pipeline. Under the hood, it uses Babel and webpack.
NPX
===
-NPX : node package executer.
-Its a Package runner/executer tool.
-It can execute any package that you want from the npm registry without even installing that package.
ex: npx create-react-app my-app
What React is
=============
-React is a JavaScript library for building user interfaces.
-It is an open-source, component based library.
-It is created & maintained by Facebook.
-React is used to build single page applications.
-React allows us to create reusable UI components.
-ReactJS uses virtual DOM based mechanism to fill in data (views) in HTML DOM.
React is NOT a framework
========================
-React is a library and not a framework.
-The difference between a library and a framework is that a library only helps
you in one aspect whereas a framework helps you in many aspects.
Let's take an example:
-React is a library because it only takes care of your UI.
-Angular, on the other hand, is a framework because it handles much more than the UI
(It handles Dependency Injection, CSS encapsulation, httpClient, Form validation, routing etc.)
Framework Library
=========================================================================
-group of libraries to make your work easier -performs specific, well-defined operations
-provides ready to use tools,standards -provides reusable functions for our code
templates for fast application development
-Collection of libraries & APIs -collection of helper functions,objects
-cann't be easily replaceable -can be easily replaceable by another
-angular,vue -jQuery,ReactJs,lodash,moment
-Hospital with full of doctors -A doctor who specializes in one
React Angular
===========================================================
1. Library-2013 1. Framework-2009
2. Light-weight 2. Heavy
3. JSX + Javascript 3. HTML + Typescript
4. Uni-Directional 4. Two-way
5. Virtual DOM 5. Regular DOM
6. Axios 6. HttpClientModule
7. No 7. Dependency Injection
8. No 8. Form Validation
9. extra libraries needed 9. No additional libraries
10. UI heavy 10. Functionality Heavy
React Features
==============
-JSX
-Components (easy to build, easy to extend,reusable,loosly coupled)
-One-way Data Binding (watchers will not be there for bindings)
-Virtual DOM
-Easy to learn because of its simple Design
-Performance
Why virtual DOM?
===============
-Frequent DOM manipulations are expensive and performance heavy.
-Every time the DOM changes, browser would need to recalculate the CSS,
run layout and repaint the web page.
-we need a way to minimize the time it takes to repaint the screen.
This is where the Virtual DOM comes in.
What Virtual DOM is
===================
-React uses virtual DOM to enhance its performance.
-Virtual DOM is a virtual representation of the real DOM.
-A virtual DOM is the DOM where a representation of the UI is kept in memory and synced with the DOM.
-When state changes occur, the virtual DOM is updated and the previous and current version of virtual DOM is compared. This is called “diffing”.
-It then makes sure that batched updates are sent to the real DOM for repainting or re-rendering of the UI.
-React never reads from real DOM, only writes to it.
How does React Work? (Virtual DOM)
====================
-A virtual DOM is a lightweight JavaScript object which is just a copy of the
real DOM. It is a node tree that lists the elements, their attributes and content as
Objects and their properties.
-React creates a VIRTUAL DOM in memory.
-Instead of manipulating the browser's DOM directly, React creates a virtual DOM in memory, where it does all the necessary manipulations, before making the changes in the browser DOM.
-React finds out what changes have been made,and changes only what
needs to be changed in the actual DOM.
-Whenever application state/props changes,
these are the steps that React performs in order to optimise performance.
a. Generate a new Virtual DOM that represents the new state of our application.
b. Compare the old Virtual DOM (which represents the current HTML DOM) vs the new Virtual
DOM.
c. Based on (b) find the minimum number of operations to transform the old Virtual DOM (which represents the current HTML DOM) into the new Virtual DOM.
What is the difference between Shadow DOM and Virtual DOM?
==========================================================
-The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components.
-The Virtual DOM is a concept implemented by libraries in JavaScript(React) on top of browser APIs.
ReactDOM
========
-ReactDOM is the glue between React and the DOM.
-React creates a virtual representation of your User Interface (what we call a Virtual DOM) and then ReactDOM is the library that efficiently updates the DOM based on the Virtual DOM.
-The reason why the Virtual DOM exists is to figure out which parts of the UI need to be updated and then batch these changes together.
-ReactDOM receives those instructions from React and then efficiently updates the DOM.
Web Browser Workflow
====================
Parsing HTML to construct DOM tree --> Render Tree construction --> Layout of the Render tree -->
-->painting the render tree.
React Reconciliation
====================
-Reconciliation is the process through which React updates the DOM.
(syncing the Virtual DOM to the actual DOM)
-Reconciliation is the mechanism that tracks changes in a component state and renders
the updated state to the screen.
-It's a step that happens between the render() function being called and the displaying of elements on the screen. This entire process is called reconciliation.
Stack Reconciler < React-16
================
-Synchronous
-works like a stack
-cann't be interrupted
Fiber Reconciler
================
-Fiber is the new reconciliation engine or re-implementation of core algorithm in React v16.
-React Fiber reconciler makes it possible to divide the work into multiple units of work(incremental rendering).
-It sets the priority of each work, and makes it possible to pause, reuse, and abort the unit of work.
-Fiber is Asynchronous.
-reconciliation and rendering to the DOM weren't separated, and React couldn't pause
its traversal to jump to other renders in between. This often resulted in lagging inputs.
-Fiber allows the reconciliation and rendering to the DOM to be split into two separate phases:
Phase 1: render(processing)
-----------------------
-React creates a list of all changes to be rendered in the UI
-Once the list is fully computed, React will schedule these changes to be executed in the next phase.
-React doesn't make any actual changes in this phase.
Phase 2: Commit
----------------
-React tells the DOM to render the changes that was created in the previous phase.
-the Reconciliation phase can be interrupted, the Commit phase cannot.
React Project - Folder Structure
================================
node_modules/ : Provides npm packages to the entire workspace. Workspace-wide node_modules dependencies are visible to all projects.
public/ : Only files inside the `public` folder can be referenced from the HTML
src/ : Source files for the root-level application project.
.gitignore : Specifies intentionally untracked files that Git should ignore.
package.json : Configures npm package dependencies that are available to all projects in the workspace.
package-lock.json : Provides version information for all packages installed into node_modules by the npm client.
README.md : Introductory documentation for the application.
React Project Flow
==================
1. index.html --> <div id="root"></div> (container to inject component)
2. index.js --> root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />)
where what
3. App.js --> AppComponent Code
JSX
===
-JSX (JavaScript Syntax Extension)is a special syntax for React that makes it easier to represent the UI.
-JSX is used to describe the structure & content of a react component.
-JSX allows us to add the elements in DOM without using createElement() or appendChild() methods.
-JSX looks similar to HTML but it is not HTML.
-JSX code we write gets transformed into React.createElement().
-JSX is not part of browser. we need a tool(Babel)(a JavaScript compiler)
to transform it to valid JavaScript.
-JSX doesn't support void tags.
<img> invalid
<img></img> valid
<img /> valid
-Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.
-ex: class becomes className in JSX, and tabindex becomes tabIndex.
React Without JSX
=================
-Code written with JSX will be converted to use React.createElement().
-we don't have to use React,createElement() when we use JSX.
Syntax : React.createElement(type,[props],[...children])
example: React.createElement(div , {name:'myDiv'},[<p> , <span>])
-The first argument is the type of element we're creating
-The second argument is props object.
-The last argument is the children of that element.
ex: <div class='test'>This is a div</div>
-Babel converts the above JSX line to the below code
return React.createElement("div", {
class: "test"
}, "This is a div");
React Element
=============
-A React element is a JavaScript object with specific properties and methods that React
assigns and uses internally.
-React elements are the instructions for how the browser DOM get created.
-When we use ReactDOM library React elements are getting changed into DOM elements.
-However, when we use React Native, React elements are getting changed into native UI elements of Android or iOS.
-We create React elements using a function called createElement().
-createElement() method is part of the Top-Level React API, and we use it to create React elements.
-This method takes three parameters:
a. The first argument defines type of element to create. (h1/p/div)
b. The second argument defines properties or attributes of the element.
c. The third argument represents the element's children, any nodes or simple text that are inserted between the opening and closing tag.
const hello = React.createElement(
"H1",
{id: "msg", className: "title"},
"Hello React Element"
);
-document.createElement() returns a DOM element (for example a div or an h1).
Whereas React.createElement() returns an object that represents the DOM element.
Module Systems
==============
1. CommonJS
module.exports = {member1,member2};
const member1 = require('Library/file name');
2. ECMASCRIPT
export member1;
export default member2;
import DefaultMember , {Namedmember} from 'file'
imports & exports
=================
-Default import:
import DefaultMember from 'src/my_lib';
-Named imports:
import { name1, name2 } from 'src/my_lib';
-Combining a default import with named imports
import DefaultMember, { name1, name2 } from 'src/my_lib';
Named Export vs Default Export
==============================
-Only one default export is allowed per file,where as multiple named exports are allowed per file.
-Named exports are useful to export several values.
-A default export can be a function, a class, an object(cann't be variables).
This value is to be considered as the “main” exported value since it will be the simplest to import
-The name of imported module has to be the same as the name of the exported module for named exports.
-The naming of import is completely independent in default export and we can use any name we like.
ex: import MyReact, { MyComponent } from "react";
correct wrong-namedExport
The React object
================
-When we import React,we get a React object that contains methods and properties.
-React exposes its current version through the version property, here's how we can read that.
import React from "react"
console.log(React.version); //"16.9.0" / 18.2.0
<h2>React Version is {React.version}</h2>
-in cmd run the below command
npm view react version
React Emmet (react snippets - plugin)
===========
https://marketplace.visualstudio.com/items?itemName=rodrigovallades.es7-react-js-snippets
IMR - import React from 'react';
IMRD - import ReactDOM from 'react-dom'
IMRC - import React, { Component } from 'react'
IMPT - import PropTypes from 'prop-types'
RCC - React class component
RCE - React class Export component
RFC - React Functional Component
RFCE - React Functional Export Component
RMC - React Function Memo component
RCONST - constructor with super
RPC - React Class Pure Component
RPCE - React Class Pure Export Component
RAFC - React Arrow Function Component
RAFCE - React Arrow Function export Component
REN - render() { return( ) }
SST - this.setState({ })
extensions
==========
1. React Snippet
2. ESLint
3. prettier
4. code spell checker
5. gitlens
6. vscode-icons
7. Thunder Client
Browser extension
=================
json viewer
React Plugins
=============
1. React Developer Tools
2. React-sight
3. Redux DevTools
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
React.StrictMode
================
-StrictMode is a tool for highlighting potential problems in a react application.
-It activates additional checks and warnings for its descendants(child elements).
-Strict mode checks are run in development mode only,they do not impact the production build.
-Strict Mode helps with the below things:
Identifying components with unsafe lifecycles (componentWillMount)
Warning about legacy string ref API usage
Warning about deprecated findDOMNode() usage
Detecting unexpected side effects
Detecting legacy context API
-ex: import React, { StrictMode } from "react";
<StrictMode>
<App />
</StrictMode>
Note: StrictMode renders components twice (on dev but not production) in order to
detect any problems with our code and warn us about them.
Component
=========
-Components are the most basic UI building block of a React application.
-Each Component is responsible for outputting a small,reusable piece of HTML.
-A Component Represents a part of the User Interface.
-Components are Re-Usable and can be nested inside other component.
-A React application contains a tree of components.
-React components let you split the UI into independent, reusable pieces,
and think about each piece in isolation.
2 types Of Component
====================
1. Functional Component ( stateless/presentational/dumb)
2. Class Component ( statefull)
-The simplest way to define a component in React is to write a JavaScript function:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
-we can also use the ES6 class syntax to write components
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
-A functional component is just a plain JavaScript function which accepts props
as an argument and returns a React element.
-Functional Components are faster and much simpler than Class Components.
-Functional components are very useful in React, especially when you want to isolate state management from the component. That’s why they are often called stateless components.
-React class components can be defined by extending React.Component or React.PureComponent.
-React component can be defined as an ES6 class that extends the base React.Component class.
-a React class component must define a render method that specifies how the component renders to the DOM.
-The render method returns React nodes, which can be defined using JSX syntax as HTML-like tags
-React requires that the first letter of a component class be capitalized.
This is required because based on capitalization JSX can tell the difference between
an HTML tag and a component instance. If the first letter of a name is capitalized,
then JSX realizes it’s a component instance; if not, then it’s an HTML tag.
Functional Component Class Component
--------------------- ---------------
1. No 'this' keyword 1. More feature rich
2. solution without state 2. Maintain own private data- state
3. Mainly for UI 3. Complex UI Logic
4. Stateless/dumb/Presentational 4. Provide Life cycle hooks
When to use a Class Component over a Function Component?
========================================================
-If the component needs state or lifecycle methods then use class component
otherwise use function component.
-However, from React 16.8 with the addition of Hooks, we can use state ,
lifecycle methods and other features that were only available in class component
in function component also.
-So, it is always recommended to use Function components, unless you need a React functionality whose Function component equivalent is not present yet, like Error Boundaries.
How to Use Bootstrap in a React application
===========================================
1. install bootstrap
npm i bootstrap@3.3.7 (particular version)
OR
npm i bootstrap (latest version)
npm i bootstrap-icons
2. use 'bootstrap.min.css' in index.js file
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap/dist/js/bootstrap.bundle.min.js";
import 'bootstrap-icons/font/bootstrap-icons.css';
How to Use Bootstrap in a React application using CDN Link
===========================================================
-Bootstrap can be used in a react application just by adding the below CDN link in 'index.html'
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
How to use Bootstrap icons
==========================
<i className="bi-alarm"></i>
<i className="bi-airplane" style={{ fontSize: "2rem", color: "cornflowerblue" }}></i>
How to use React-icons
======================
1. install react-icons
npm install react-icons
2. import react-icons in component
import { FaEdit, FaTrash } from 'react-icons/fa';
import { BsFillCalendarDateFill,BsFillClockFill } from 'react-icons/bs';
3. use the Icons
<FaEdit />
<FaTrash color='red' />
Fragments
==========
-While returning elements in JSX, we can only return 1 element at a time.
That element can have children but we have to ensure that we are only returning 1 element at a time, or else we will get a syntax error. (ex: a function can return 1 value)
-Fragments are way to render multiple elements without using a wrapper element.
-Fragment acts as a wrapper without adding unnecessary divs to the DOM.
-We can use it directly from the React import, or deconstruct it.
import React from 'react';
<React.Fragment>
<div>I am an element!</div>
<button>I am another element</button>
</React.Fragment>
-// Deconstructed
import { Fragment } from 'react';
<Fragment>
<div>I am an element!</div>
<button>I am another element</button>
</Fragment>
-React version 16.2 simplified this process further, allowing for empty JSX tags to be interpreted as Fragments
<>
<div>I am an element!</div>
<button>I am another element</button>
</>
Data Binding
============
-Binding/Displaying the variable value in UI is called data binding.
CSS in React
============
different ways to add CSS:
1. inline CSS
2. External CSS
3. global css(index.css)
4. CSS Modules
5. Conditional CSS
CSS Modules
===========
-This approach is designed to fix the problem of the global scope in CSS.
-A CSS Module is a CSS file in which all class names are scoped locally by default.
-CSS Modules allow to use the same CSS class name in different files without worrying about naming clashes.
-CSS Modules allow the scoping of CSS by automatically creating a unique classname of the below format.
ex: [filename]\_[classname]\_\_[hash]
-ClassNames are dynamically generated, unique, and mapped to the correct styles.
-When importing the CSS Module from a JS Module, it exports an object.
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
<button className={styles.error}>Error Button</button>;
-it will only apply the classname from css module even if both files have same 'error' class;
Conditional Rendering
=====================
-It is a common use case to show or hide elements based on certain conditions.
-it allows us to render different elements or components based on a condition.
-use cases:
Rendering external data from an API.
Showing or hiding elements.
Toggling application functionality.
Implementing permission levels.
Handling authentication and authorization.
-ways to implement conditional rendering:
Using an if…else Statement
Using a switch Statement
Using Ternary Operators
Using Logical && (Short Circuit Evaluation)
Ternary- <div>{flag ? <h1>Helllloooooo</h1> : null}</div>
Short Circuit- <div>{flag && <h1>Helllloooooo</h1>}</div>
List Items - Lists and Keys
===========================
-A 'key' is a special attribute which should be included while creating List Items.
-There will be a warning message in the console if the key prop is not present on list items.
-'Key' gives the elements a stable unique Identity.
-'Key' helps react to identify which items have changed,are added, or removed.
-React relies on the key to identify items in the list.
React uses a virtual DOM, and it only re-draws the components that changed since the last render.
-The first time a component like IdiomaticReactList is rendered, React will see that you want to render a bunch of items, and it will create DOM nodes for them.
-The next time that component renders, React will say, “I already have some list items on screen are these ones different?” It will avoid recreating DOM nodes if it can tell that the items are the same.
-Tip: Avoid using the index as key, if the list is filtered or sorted
it will cause the key value to change to the new index and React will consider
them different elements and repaint the whole list.
-Why map() is used to iterate array instead of forEach()
JSX needs an array of items to render,forEach() does not return anything (i.e it returns undefined). map() returns an array.
read data from a JSON file
==========================
1. create a JSON file (employees.json/products.json/countries.json)
[ {},{},{} ]
2. import listData from './countries.json'
3. use 'listData' in JSX
{countries.map((country,ind)=>{
return <option key={ind} value={country} />
})}
Assignment
==========
1. create products.json with list of products.
https://fakestoreapi.com/products
2. display the products in table & card
forceUpdate
===========
-Declaring class variables/function variables is always a bad idea.
-can be used for the below 2 use cases:
Setting and clearing timeouts
Storing frequently-referenced values
-React components will only re-render when there are changes to props or state.
-Updating the class/function variable does not trigger a re-render.
-Its our responsibility of triggering the re-render when our class data changes.
-Normally we should try to avoid all uses of forceUpdate() and only read from
this.props and this.state in render().
-In class components,this.forceUpdate() is used to force a re-render.
-In Functional components,there is no concept of force re-render.
props
=====
-Props are inputs to components.
-Props stand for properties and is a special keyword in React.
-Attributes on Components get converted into an object called Props.
-Helps to Pass custom data to a component.
-props are used to pass data and methods from a parent component to a child component.
-data with props are being passed in a uni-directional flow. (one way from parent to child).
-We can pass props to any component as we declare attributes for any HTML tag
<ChildComponent someAttribute={value} anotherAttribute={value}/>
-React props passed with just their name have a value of true.
<myComponent showTitle={true}>
<myComponent showTitle>
-The props can be accessed as shown below
this.props.propName; (Class Component)
props.propName; (Functional Component)
1.They are immutable. data coming from the parent should not be changed by child components. we will get an error if you try to change their value.
2.data with props are being passed in a uni-directional flow. (one way from parent to child)
Props De-structuring
====================
-It’s a JavaScript feature that allows us to extract multiple pieces of data from an array or object and assign them to their own variables.
-Improves readability.
-we can get rid of props/this.props in front of each property.
-props de-structuring in functional component
export default function Greet({ name, msg }){}
-we de-structure props in the render() function.(class Component)
ex: let { pId, name, price } = this.props.product;
PropTypes
=========
-React has some built-in typechecking abilities.
-To run typechecking on the props for a component,we can assign the special propTypes property.
-PropTypes exports a range of validators that can be used to make sure the data the component receive is valid.
-When an invalid value is provided for a prop, a warning will be shown in the browser console.
-For performance reasons, propTypes is only checked in development mode.not in production.
1. import PropTypes from 'prop-types';
2. ComponentName.propTypes = {
variableName: PropTypes.string
};
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
optionalElement: PropTypes.element,
optionalEnum: PropTypes.oneOf(['News', 'Photos']),
optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
}),
Requiring Props
===============
-If prop values are not passed to a certain component, no error will be thrown.
Instead, within the component that prop will have a value of 'undefined'.
-Apart from specifying the type of the prop that can be passed to the component,
we can also make sure the prop is always provided to the component by chaining
isRequired at the end of the prop validator.
Student.propTypes = {
name: PropTypes.string.isRequired, // Required Prop
age: PropTypes.number // Optional Prop
}
Default props
=============
-defaultProps allows to set default value for props.
-ex:
Greet.defaultProps = {
msg: 'this is my default message'
}
-Functional Component & destructuring
export default function Greet({name , msg='good morning'}) {
}
Props.children
==============
-props.children represents the content between the tags of a Component.
-props.children can be an array or a single item.
-props.children is available on every component.
-<Welcome>Hello world!</Welcome>
-The string Hello world! is available in props.children in the Welcome component.
-class Welcome extends React.Component {
render() {
return <p>{this.props.children}</p>;
}
}
Ensuring Single Child
=====================
-We can use PropTypes.element to enforce that only a single child can be passed
to a component as children.
-If we try to pass more than 1 child to the component, we will get an error.
Ex:
Greet.propTypes = {
children: PropTypes.element
};
Prop Drilling
=============
-Prop drilling is the process in a React app where props are passed from one component to another by going through other parts that do not need the data, but only help in passing it through the intermediate components.
-The problem with this approach is that most of the components through which this data is passed have no actual need for this data.
-They are simply used as mediums for transporting this data to its destination component.
-as the components are forced to take in unrelated data and pass it to the next component, which in turn passes it, and so on, until it reaches its destination.
This can cause major issues with component reusability and app performance.
-This Problem Can be avoided by using concepts like 'Context API' & 'REDUX'
States
======
-the State of a component is an object that holds some information
that may change over the lifetime of the component.
-whenever the state object changes,react will re-render the component.
render() gets re-invoked.
State in Class Component
========================
-class components have a state object , where all the state variables are declared.
To update state variables, setState() should be used;
-State object is usually initialized inside the constructor in class components.
-UI will not Re-render when we change state directly, setState() should be used.
this.counter = this.counter + 1; // re-render won't happpen
this.setState({counter:this.state.counter+1}); // re-render will happpen
-use setState() to change the state of react Component.
it ensures that render() gets called.
-If a piece of code needs to be executed only after the state has been updated, then
place that code in the callback function which is the second arguement to setState()
Syntax: setState( StateObject, callbackFunction);
ex: setState( {} , ()=>{} );
Note:
-----
-setState() actions are asynchronous. setState() doesn’t immediately mutate this.state.
-React may group multiple setState() calls in to a single update for better performance
-when we want to update the state based on the previous State value,
we need to pass a function as an arguement to setState() instead passing an object.
ex:- this.setState({ value: this.state.value + 1 });
this.setState(prevState => ({ value: prevState.value + 1 }));
State in Functional Component
=============================
-State in functional Component can be maintained using useState() hook.
-useState() is used to declare a state variable in function component.
-The only argument to the useState() Hook is the initial state.
-It returns a pair of values:
a. the current state
b. a function that updates the state.
ex: const [count, setCount] = useState(0);
-state updation is asynchronous,
const increment = () => {
setCount(count + 1);
console.log(count); // this will be executed before state update
};
-If a piece of code needs to be executed only after the state has been updated, then place that code in the 'useEffect()'
-when we want to update the state based on the previous State value,pass a callBack to setter
ex: setCount((prevState) => prevState + 1);
setCount(count + 1);
Props vs State
=======================================================================
1. Props are immutable. 1. State is mutable/modifiable.
2. pass data from parent component 2. contains own data & changes over time
to child component
3. communicate between components 3. rendering dynamic changes
4. props - Functional Comp 4. useState() - Functional Comp
this.props - class comp this.state={} - Class Comp
How to use SweetAlert
=====================
https://sweetalert2.github.io/#examples
1. npm i sweetalert2
2. import Swal from 'sweetalert2'
3. on button click call a function, which has the below code
Swal.fire(
'Good job!',
'You clicked the button!',
'success'
)
How to use react-modal
======================
1. npm i react-modal
2. import Modal from 'react-modal';
3. use Modal as below
let [modalIsOpen, setIsOpen] = useState(false);
function openModal() {
setIsOpen(true);
}
function closeModal() {
setIsOpen(false);
}
<>
<button onClick={openModal}>Open Modal</button>
<Modal
isOpen={modalIsOpen}
onRequestClose={closeModal}
contentLabel="Example Modal"
>
<h2>Hello Hiiiiiiiiiii</h2>
<button onClick={closeModal}>close</button>
<div>I am a modal</div>
</Modal>
</>
How to use react-bootstrap modal
================================
1. npm install react-bootstrap bootstrap
2. import Modal from 'react-bootstrap/Modal';
3. const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
<Button variant="primary" onClick={handleClose}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
<Button onClick={handleShow}>click me</Button>
Search
======
1. Install react-js-search from npm
npm i react-js-search
2. Import SearchBar in your react component
import SearchBar from 'react-js-search';
3. use the below HTML
<SearchBar
onSearchTextChange={(term, filteredData) => {
setFilteredEmployees([...filteredData]);
}}
onSearchButtonClick={onSearchClick}
placeHolderText={"Search here..."}
data={employees}
/>
Pagination
==========
1. npm install react-paginate
2. import ReactPaginate from 'react-paginate';
3. <Employees> / <Products> / <Users>
<ReactPaginate
breakLabel="..."
nextLabel="next >"
onPageChange={handlePageClick}
pageRangeDisplayed={5}
pageCount={pageCount}
previousLabel="< previous"
renderOnZeroPageCount={null}
/>