-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReactJS-learning.txt
More file actions
493 lines (282 loc) · 12.2 KB
/
ReactJS-learning.txt
File metadata and controls
493 lines (282 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
* React is a Javascript library which is developed by Facebook in 2011 & is used to create fast and interactive user interfaces.
* Every React app will contain at least one main component which we refer to 'root' component.
* Every React app is essentially a tree of components.
* Each component is a pieace of UI.
* In terms of implementation a component is implemeted as a javascript class that has some "state" and a "render" method.
* class Tweet {
state = {};
render() {
return <h1>Hello world</h1>
}
}
* Here the "state" is the data that we want to display when the component is render.
* And the "render" method is responsible for discribing what the UI should look like.
* React = React to state changes. Because when the state changes React essentially reacts to the state change and updates the DOM.
* Both Angular & React are similar in terms of their component based architecture, However Angular is a Framework and a complete solution while React is library.
*
* To create React app, first we need to install react globally with below command
-> npm i -g create-react-app
* To know globally installed react-app version use below command
-> create-react-app --version
* Now use below command to create react app.
-> create-react-app [app name]
* By default the above command installs
Development server, Webpack, Babel and other few libraries we need.
* By default React provides "react", "react-dom" & "react-scripts" dependencies.
* 'Babel' is a "Modern Javascript Compier" and is used to compile our javascript code.
* 'Babel' takes 'jsx' syntax and converts it to plain javascript that browser can understand.
* By default we get below folders
node_modules, public & src
* By default we get below files
.gitignore, packet.json, packet-lock.json & README.md
* Index.html file will reside in 'public' folder
* In React we have .jsx which stands for "Javascript XML"
* 'jsx' is used for discribing UI.
* React contains "Hot Module Reloading" feature in-built.
* To use "bootstrap" in react app, first we need to install it using below command
-> npm i bootstrap@latest
then we need to import bootstrap in 'index.js' file as below
-> import 'boorstrap/dist/css/bootstrap.css';
If the above path doesn't work then use below path
-> import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
* If we want to use "Font-Awesome" then simply paste the "Font-Awesome" URL in "index.html" file.
* 'React' module will call "React.createElement" internally.
* "React.Fragment" element can be used to ommit wrapper div inside of 'render' method.
Ex: class Counter extends Component {
state = {
count: 0
}
render () {
return (
<React.Fragment>
<span> { this.state.count } </span>
<button> Increament </button>
</React.Fragment>
);
}
}
* 'state' is a special property in react components, basically it's an object which includes any data that this component needs.
* 'JSX' are just like normal javascript objects. We can return them from a function, we can pass them to a function. We can also use then as constant OR a variable.
* Setting an attribute to an element
state = {
count: 0,
imageUrl: 'http://picsum.photos.com/200'
}
<img src={this.state.imageUrl} alt="" />
* If we want apply any classes on element then we need to use "className" but not "class".
And we need to use "style" attribute as below.
Note: We should follow "camelCase" notation for "class"es and for "css attributes" as below.
Ex: class Counter extends Component {
state = {
count: 0
}
styles = {
fontSize: 10,
fontWeight: "bold"
}
render () {
return (
<div>
<span style = { this.styles } className="btn btin-primary m-2">{this.formatCount()}</span>
<button>Increment</button>
</div>
)
}
formatCount(){
let { count } = this.state;
return if(count === 0) ? 'Zero' : count;
}
}
export default Counter;
* We can also use in-line styles as below
Ex: <span style = {{fontSize: 30}} className="btn btin-primary m-2">{this.formatCount}</span>
* Rendering classes dynamically
Ex: render() {
let classes = "badge m-2 badge-";
classes += (this.state.count === 0) ? "warning" : "primary";
return ( <span className={classes}>{this.formatCount}</span> );
}
Note: Did you notice that we didn't use 'this' keyword while calling "classes" class name? It's because that "classes" variable is declared inside of "render" method.
* Always use descriptive names that determine the intension of your code.
* Since "jsx" is not a template engine, Unlike "Angular" we don't have "if else" conditions.
* Every React component contains a property called "props".
*** Difference B/W PROPS & STATE ***
* "props" includes data that we give to a component.
* "state" includes data that is local or private to that component, other component can not access that state.
* "props" are 'readonly' in other words, we can't change the provided properties to a component inside of it's component.
* The component that owns a piece of the state, should be the one modifying it.
* We need to follow "Single Source of Truth" principle.
* "Controlled component" concept
* In situation like that when there is no parent child relationship B/W two components and you want to keep then in sync & you want to share data B/W them then you need to lift the state up.
* We can use "this" in class components only but not in "Stateless functional components"
* If we use "Stateless functional components" then we need to pass "props" as an agrument to use "props" in return method.
Ex: const Navbar = props => {
return (
<nav className="navbar navbar-light bg-light">
<span className="navbar-brand">
Navbar
<span className="badge m-2 badge-pill badge-primary">
{props.totalCounters}
</span>
</span>
</nav>
);
};
* Destructuring Arguments in SFC : In above example can be re-written like below
Ex: const Navbar = ({totalCounters}) => {
return (
<nav className="navbar navbar-light bg-light">
<span className="navbar-brand">
Navbar
<span className="badge m-2 badge-pill badge-primary">
{totalCounters}
</span>
</span>
</nav>
);
};
* Destructuring Arguments in CC :
-> Actual code (Before destructuring):
render() {
return (
<div>
<button
onClick={this.props.onReset}
className="btn btn-primary btn-sm m-2"
>
Reset
</button>
{this.props.counters.map(counter => (
<Counter
key={counter.id}
onDelete={this.props.onDelete}
onIncrement={this.props.onIncrement}
counter={counter}
/>
))}
</div>
);
}
-> After destructuring:
render() {
const { onReset, counters, onDelete, onIncrement } = this.props;
return (
<div>
<button
onClick={onReset}
className="btn btn-primary btn-sm m-2"
>
Reset
</button>
{counters.map(counter => (
<Counter
key={counter.id}
onDelete={onDelete}
onIncrement={onIncrement}
counter={counter}
/>
))}
</div>
);
}
Actions Done:
--------------------------------------------------------------------------------------------
* JSX
* Rendering lists
* Conditional Rendering
* Handling Events
* Updating the State
* Passing Data B/W components
* Raise and Handle Events B/W components
* Multiple Components in Sync
* Functional Components
* Lifecycle Hooks
* Lifing the state up
* Bubbling events to parent component
* Stateless Functional Components
* Destructuring Arguments
* Lifecycle Hooks (phase)
-> Mountain phase = Where instance of a component is created & inserted into the DOM
-> constructor
-> render
-> componentDidMount
* React will call these methods in order.
-> Update
-> render
-> componentDidUpdate
* This happens when the state or the props of a component get changed.
-> Unmount
-> componentWillUnmount
* This happens when component is removed from DOM such when we delete a counter (as per our example)
Note: There are few methods we can add to the components and React will automatically call all these methods. We refer these methods as "Lifecycle Hooks", so they allow us hook into certain moments during the lifecycle of a component and do something.
We have other lifecycle hooks also, but we use then very rarely.
* We can not use "props" inside of "constructor" method unless we pass "props" as parameter to 'constructor' and 'super' methods, otherwise 'this.props' will return 'undeined'.
Ex: constructor (props){
super(props);
this.state = props;
}
* 'constructor' method is the right place to initialize properties in this class.
* 'componentDidMount' will be triggered after component is rendered into the DOM. It is the perfect place to make AJAX calls to get data from server.
Ex: componentDidMount(){
// AJAX call
this.setState({movies});
}
* Point to be noted: When component is rendered it means all it's child components also rendered recursively.
* Point to be noted: We can not use 'lifecycle hooks' in 'stateless functional components'.
* 'componentWillUnmount' phase will be triggered just before a component is removed from DOM. We can do anything of cleanups like if we set up like timers or listners, to avoid memory leaks here.
* To implement routing we need follow two things
-> We need to import "BrowserRouter" from "react-router-dom" in index.js
* import { BrowserRouter } from "react-router-dom";
-> Then we need to wrap <App /> with <BrowserRouter>, as below
* <BrowserRouter><App /></BrowserRouter>
* Registering routes
-> We can use 'exact' OR
-> Can import "Switch" module from "react-router-dom"
* We should impletemt 'a' tag as below, but we need to import "Link" module from "react-router-dom"
-> <Link to="/">Home</Link>
* Router props are "history", "location" & "match"
* Passing props
<Route path="/products" render={(props) => <Products sortBy="newest" {...props} />} />
* Router params
-> <Route path="/products/:id" component={ProductDetails} />
-> In 'ProductDetails' component, <h1>Product Details - {this.props.match.params.id}</h1>
* Optional Route Params
-> <Route path="/posts/:year?/:month?" component={Posts} />
* Query String: To extract query strings we need to install "query-string" package using npm
* We use 'match' object to extract the route parameters.
* Query Strings will be in "location" object.
* Redirects:
<Redirect from="/messages" to="/posts" />
* Programmatic navigation:
this.props.history.push("/products");
this.props.history.replace("/products");
* Nested routing:
Short & Sweet:
--------------------------------------------------------------------------------------------
* In Javascript unlike other proramming languages we can apply the logical and (&&) between non-boolean values. Below two are examples
-> conole.log(true && "hi"); // returns "hi"
-> conole.log(true && "hi" && 1); // returns 1
* To add routing to the DOM we need to install library called "react-router-dom"
React commands:
------------------------------------------------------------------
* npm i -g create-react-app
* create-react [app name] | npx create-react [app name] .
* npm start --> This will start our dev server on port 3000 by default
* npm run build --> To build the app for deployment - It generates "build" folder
Shortcuts, can be used in VS code:
------------------------------------------------------------------
* imrc = imports React and React component module.
* imr = imports React module
* cc = class component
* sfc = stateless functional component.
Note: We use 'imr' in 'sfc'
Other:
------------------------------------------------------------------------
* "Ayu Mirage" is the theme Mosh is using.
=================================== Vidly Application ======================================
* npx create-react-app .
* npm i bootstrap@4.1.1 font-awesome@4.7.0 prop-types@15.6.2 react-router-dom@4.3.1 query-string@6.1.0
*
*
* table.table>thead>tr>th*4
* div.col-1+div.col