-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact.txt
More file actions
626 lines (471 loc) · 14.8 KB
/
Copy pathreact.txt
File metadata and controls
626 lines (471 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
React Vite Project Setup & Basics
==================================
🚀 Project Setup
----------------
1. Create Vite Project
npm create vite@latest
- Enter project name
- Select React
- Choose JavaScript or TypeScript variant
2. Navigate to Project
cd project-name
3. Install Dependencies
npm install
4. Install Latest React (React 19)
npm install react@latest react-dom@latest
5. Start Development Server
npm run dev
Visit: http://localhost:5173
📂 Project Structure
--------------------
project-name/
├── index.html
└── src/
├── main.jsx
├── App.jsx
└── components/
└── Comp-01.jsx
Component Flow:
Component → App.jsx → main.jsx → index.html
⚙️ React Basics
---------------
1. Component Naming
- Component names must start with Capital Letters.
2. Component Syntax
const ComponentName = () => {
return (
<div>
{/* Content here */}
</div>
);
};
3. Exporting Components
export default ComponentName;
4. Using Components
Import in App.jsx:
import ComponentName from './components/ComponentName.jsx';
Use inside App:
const App = () => {
return (
<div>
<ComponentName />
</div>
);
};
export default App;
5. Single Parent Element
- Each component must return exactly one parent element.
6. JSX Syntax Differences
HTML Attribute JSX Equivalent
-------------- --------------
class className
for htmlFor
id id
7. Expressions in JSX
- Write JavaScript expressions inside {}:
<p>{2 + 2}</p> // Outputs: 4
- Dynamic class names:
<div className={dynamicClass}></div>
8. Rendering Lists
const items = ['Item1', 'Item2', 'Item3'];
export const List = () => {
return (
<div>
<ol>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ol>
</div>
);
};
9. Destructuring Array of Objects in Components
const users = [
{ name: 'Alice', email: 'alice@example.com', location: 'NY', jobRole: 'Developer' },
{ name: 'Bob', email: 'bob@example.com', location: 'LA', jobRole: 'Designer' },
];
export const UserList = () => {
return (
<div>
{users.map(({ name, email, location, jobRole }, index) => (
<ol key={index}>
<li>Name: {name}</li>
<li>Email: {email}</li>
<li>Location: {location}</li>
<li>Job Role: {jobRole}</li>
</ol>
))}
</div>
);
};
10. Props (Properties)
- Props are arguments passed from a parent to a child component.
Passing Props from Parent:
<PropsChild name="Sayoun" gmail="0xSYN.dev@gmail.com" />
Using Props in Child (Destructuring):
export const PropsChild = ({ name, gmail }) => {
return (
<div>
<p>{name}</p>
<p>{gmail}</p>
</div>
);
};
11. Conditional Rendering
- Conditionally display different components or content based on props or state.
Passing Prop from Parent:
<ConditionalRender isValid={false} />
Conditional Rendering in Child:
const ValidPassword = () => <h1>Valid Password</h1>;
const InvalidPassword = () => <h1>Invalid Password</h1>;
export const ConditionalRender = ({ isValid }) => {
if (isValid) {
return <ValidPassword />;
}
return <InvalidPassword />;
};
12. Styling IN JSX
a- Inline Style [use two {{}} in inline ] - <h1 style={{color: "red", textAlign:"center"}}>Inline Style</h1
b- JS object as style
const styles = {
color: "green",
backgroundColor: "crimson",
padding: "2rem",
textAlign: "center",
};
//Using it in the Component
<h2 style={styles}>JS Object as style</h2>
c- CSS importing index.css
import("./index.css");
13. Icons [Libraries]
a- React Icons [Use by installing]
npm install react-icons
//Importing icon
import { DiLinux } from "react-icons/di";
//Using icon
<DiLinux siize={30} color="white"/>
14. Event handler
a-onClick()
export const EventHandler = () => {
const handleClick = () => {
return console.log("haandleClick button clicked!");
};
return <button onClick={handleClick}>Click</button>;
};
b-onCopy()
<p onCopy={copyhandler}>Don't coy the paragraph</p>
15. STATE and HOOKS
-State is a way to store and manage data that can change over time and affects how the components renders. We define state using the useState Hook, which allows you to set an initial value and provides a way to update that state.
-Hooks are a new addition in react 16.8 They let you use state and other React features without writing a class.
-What is useState() - it is a hook which allows us to track state in a functional component. State generally refers to data or properties that need to be tracking in an application.
syntax - const [data , changeData]= useState()
1. useState with normal numbers
import { useState } from "react";
export const StatesHooks = () => {
const [count, setcount] = useState(0);
const increment = () => setcount(count + 1);
const decrement = () => setcount(count - 1);
return (
<div>
<h1>{count}</h1>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
};
2. useState with array
const [friends, setFriends] = useState(["Sayoun", "Alex", "John", "Michel"]);
const addNewFriend = () => setFriends([...friends, "New Friend"]);
const removeFriend = () => setFriends(friends.filter((f) => f != "John"));
const updateFriend = () => {
setFriends(friends.map((f) => (f === "Alex" ? "Alex Smith" : f)));
};
3. usestate with object
const [movie, setMovie] = useState({
title: "Endagame",
ratings: 9.8,
});
const handleClickRating = () => {
//update long way
// const copymovies = {
// ...movie,
// ratings: 5,
// };
// setMovie(copymovies);
//update object short hand way
setMovie({ ...movie, ratings: 10 });
};
4. useState with array of objects
const [arrayMovies, setarrayMovies] = useState([
{ id: 1, title: "Avangers: EndGame", ratings: 9.8 },
{ id: 2, title: "Spider-man HomeComing", ratings: 8.9 },
]);
const changeName = () => {
setarrayMovies(
arrayMovies.map((m) =>
m.id === 1 ? { ...arrayMovies, title: "John Wick 4" , ratings: 9 } : m
)
);
};
Share State into another component
//This is from parent Component
<Comp1 count={count} onClickHandler={() => setCount(count + 1)} />
---------This is comp1
-Below is child comp code click and onClickHandler are destructured in child and used
export const Comp1 = ({ count, onClickHandler }) => {
const handleClick = onClickHandler;
return (
<div>
<h3>Comp1 Counter</h3>
<p>{count}</p>
<button onClick={handleClick}> + </button>
</div>
);
};
------ This is comp2
export const Comp2 = ({ count, onClickHandler }) => {
const handleClick = onClickHandler;
return (
<div>
<h3>Comp1 Counter</h3>
<p>{count}</p>
<button onClick={handleClick}> + </button>
</div>
);
};
clicking one will update both
-Passing arrow function in useState
import { useState } from "react";
export const ArrowUseState = () => {
const [count, setCount] = useState(() => {
const initialCount = 10;
return initialCount;
});
const increment = () => {
setCount((prevCount) => prevCount + 1);
};
return <div>
<h1>Counr: {count}</h1>
<button onClick={increment}>Increment</button>
</div>;
};
-Another example
const [randomNumber, setRandomNumber] = useState(() => {
const randomNumber = Math.floor(Math.random() * 100);
return randomNumber;
});
const generateRandomNumber = () => {
const newNumber = Math.floor(Math.random() * 100);
setRandomNumber(newNumber);
};
----- Best Example of useState and useEfect
import { useState, useEffect } from "react";
const StateEffect = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchUsers = async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await response.json();
setUsers(data);
setLoading(false);
} catch (err) {
console.log("Error caught:", err);
}
};
fetchUsers();
}, []);
return (
<div>
<h2>Users List from API</h2>
{loading ? (
<p>Loading users...</p>
) : (
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} ({user.email})
</li>
))}
</ul>
)}
</div>
);
};
export default StateEffect;
Note - can't we change the count value without setCount like count ++ ;
The answer is no cause behind the scene the counter will update but ui will not that's why setCount is used it will re-render that part of the ui.
React Portal:
Portal is a feature that allows you to render a child component into a ODM node that exists outside the hierarchy of the parent component. This can be useful for scenarios like modals, tooltips or dropdowns , where you want to break out of the usual parent-child structure and render in different part of the DOM
Portals are majorly used for modals, tooltips and dropdowns
Step 1. Add a div to main
<body>
<div id="root"></div>
<div id="modal-root"></div> <!-- For Portals -->
</body>
Step 2. Create portal component
import React from 'react';
import ReactDOM from 'react-dom';
const Modal = ({ children }) => {
const modalRoot = document.getElementById('modal-root');
return ReactDOM.createPortal(
<div className="modal">{children}</div>,
modalRoot
);
};
export default Modal;
Step 3. Import it and render using useState and &&
import React, { useState } from 'react';
import Modal from './Modal';
function App() {
const [showModal, setShowModal] = useState(false);
return (
<div className="App">
<h1>Hello React</h1>
<button onClick={() => setShowModal(true)}>Open Modal</button>
{showModal && (
<Modal> // here its like passing props but diff htmlm as props
<div className="modal-content">
<h2>I am a Portal Modal</h2>
<button onClick={() => setShowModal(false)}>Close</button>
</div>
</Modal>
)}
</div>
);
}
// Copy to clipboard component
import { useState } from "react";
import { PopUpCopied } from "./PopUpCopied";
export const CopyInput = () => {
const [inputValue, setIpnutValue] = useState("");
const [copied, setCopied] = useState(false);
const handleCopy = () => {
navigator.clipboard.writeText(inputValue).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
});
};
return (
<div >
<input
type="text"
value={inputValue}
onChange={(e) => setIpnutValue(e.target.value)}
/>
<button onClick={handleCopy}>Copy text</button>
<PopUpCopied copied={copied} />
</div>
);
};
// that pop up - copied to clipboard
export const PopUpCopied = ({ copied }) => {
return (
<div style={{ position: "relative", paddingBottom: "4rem" }}>
{copied && (
<div style={{ position: "absolute", bottom: "3rem" }}>
Copied to clipboard
</div>
)}
</div>
);
};
--- Prop Drilling -In React, prop drilling refers to the process of passing data from a parent component to deeply nested child components via intermediate components that do not necessarily need the data themselves.
This leads to:
- Verbose and repetitive code
- Tightly coupled components
- Difficult maintainability
- Problems when state or data structures change
When it becomes unmanageable, the preferred solutions are:
- React Context API
- State management libraries like Redux, Zustand, Jotai, etc.
---ContextAPI - IT is feature that allows you to manage and share state across your component tree without having to pass props down manually at every level.
--- createContext(), useContext()
CODE -
-app.js <Parent />
-Parent.js
import { createContext } from "react";
import { Child } from "./Child";
export const DataContext = createContext();
export const Parent = () => {
const user = {
name: "Sayoun",
age: 21,
email: "sayoun@example.com",
};
return (
// Value passed from here i.e name
<DataContext.Provider value={user}>
<Child />
</DataContext.Provider>
);
};
-Child.js
import { useContext } from "react";
import { DataContext } from "./Parent";
export const Child = () => {
const { name, age, email } = useContext(DataContext);
return (
<div>
<h2>Data received from Parent via Context:</h2>
<p>Name: {name}</p>
<p>Age: {age}</p>
<p>Email: {email}</p>
</div>
);
};
-- useReducer() - is a hook that is to useState, but it is designed for more complex state objects or states transitions that involves multiple sub values. It allows you to manage state in a functional , immutable way.
Syntx -
const [state, dispatch] = useReducer(reducer, initialState)
Code-
import { useReducer } from "react";
const initialState = { count: 0 };
const reducer = (state, action) => {
switch (action.type) {
case "increment":
return { ...state, count: state.count + 1 };
case "decrement":
return { ...state, count: state.count - 1 };
case "reset":
return { ...state, count: 0 };
default:
break;
}
};
export const Reducer = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<h1>Count: {state.count}</h1>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<button onClick={() => dispatch({ type: "reset" })}>Reset</button>
</div>
);
};
----useRef() - this hook provides a way to access and interact with DOM elements or to persist values across renders without causing a re-render.
Syntx-
const myRef = useRef(initialValue);
-- Custom Hooks - These are JS functions that start with the prefix use(eg. useFetch, useForm etc) and can call other hooks within them. They allow you to extract and reuse logic that involves state or side effects, making your components more readable and maintainable.
Example -
const useFetch = (url)=>{
const [data, setData] = useState(null);
useEffect(()=>{
fetch(url).then(res)=>res.json()).then((data)=>setData(data));
}, [url]);
return data;
}
//Inside another comp using useFetch
const [data] = useFetch("https://random-url.com/data);
return (
<>
{data && data.map((item) => (
<ul key={item.id}>
<li>{item.name}</li>
</ul>
))}
</>
);
//---------useId - It is a hook in react is used to generate unique IDs for components
const id = uniqueId();