-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheatsheet.txt
495 lines (436 loc) · 19.2 KB
/
cheatsheet.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
---- Cheatsheet for REACT ----
- npx create-react-app my-app
- npm install @mui/material @emotion/react @emotion/styled
- npm install @mui/icons-material
-- component creation --
- uppercase naming should be done
- they are basically a function and nothing else buddy
const ExpenseItem = () => {
return <div>Hey there buddy</div>;
};
export default ExpenseItem;
- importing css file inside component
import "./ExpenseItem.css";
- passing props
<ExpenseItem title="toilet Paper" name={name} />
- extracting props
const ExpenseItem = (props) => {
-- concept of children props is there (do look into it if you are interested)
(basically creating wrapper components if you are interested in)
-- some concepts regarding JSX theory and stuff
- adding functionality on button clicking
<button onClick={clickHandler}>Change Title</button>
----- useState theory ----
- you component is a function that returns JSX
- You never call these functions, but under the hood they are pretty much like function calls!!!
- and react never repeats that, simple as that
- but sometimes you want to render that function again, and for the we use state
import { useState } from "react";
const [namer, setNamer] = useState("shitty");
const clickHandler = () => {
setNamer("random");
};
- UNDERSTAND IT FULLY
- this way any change inside the function will re-render all the stuff that was before, simple as that
- IMPORTANT -- all the variable changes you do which are not state, will be there, but if you wanna see them, you got to update a state variable
and then you can simply all those values that those variables were having, only the render part is not happening, everything else is!!! How cool is that ---
- and only when one state changes, that only instance is called, like if four expenseItem are there
- only one is going to render again, and print some console log stuff and not any other!!!!!
- why using const??? we never know how react is storing that variable, simple as that, react provided the latest state stored
- react keeps track of when we call the function first time, simple!!! hence initial value is only considered for the first time and nothing else
- using event functionality in a function -- (simple as that)
const inputHandler = (event) => {
setInputValue(event.target.value);
console.log(event.target.value);
};
- you can have mutliple states in a component, simple as that, always remember that
-- One more alternative, using only one state (YOU CAN LEARN IT IF YOU WANT TO) ---
-- simply new useState would store some object, and you have to simply manage it and figure it out ---
-- whenever you update an state, which uses the state provided by the previous state, you should be doing this below stuff
const inputtHanlder = (event) => {
setInputValue((prevState) => {
return "some value using previous vaue";
});
};
--- Removing default behaviour for submitting form (simple)
const submitHandler = (event) => {
event.preventDefault();
--- To way binding ---
<div>
<label>Name</label>
<input
type="text"
id="name"
value={inputValue} --- you are giving this value back!! simples (no infininte loop in there)
onChange={inputHandler}
/>
</div>
--- child to parent communication --
<button onClick={props.normalHandler}>increse count</button>
(basically passing function to child components, so that we can pass the data up!!)
-- Lifting state up!!!! ---
--> NewExpense -- data, state is generated here
--> Expense -- they need to use state!!
--> App -- Hence they will keep the state!!!!!! How important, close involved component should have it!!
-- Controlled Uncontrolled State Stateless ---- (read it again if you want to!!! Not interested)
---- Rendering list and conditional stuff -----
- simple map also works in here if you want to, it returns these values
{data.map((cdata) => {
return <ExpenseItem name={cdata.name}></ExpenseItem>;
})}
-- understanding keys -- (you can read more if you want)
- rendering keys without performance loss and stuff if you think about it --
- some theory is there, basically react doesn't know much clearly what to update and what not
- updates all items and shit, which is not at all optimised
- hence having key makes updates only possible at specific positions
- bugs could happens as well
- key props could be added if you want!!!
--- conditional rendering --- (simple shit)
{data.length === 0 && <p>Nothing is there</p>}
{data.length > 0 && data.map((cdata) => {
return <ExpenseItem name={cdata.name}></ExpenseItem>;
})}
---- Using return statements inside a component ----
if (data.length === 0) return <p>Nothing is here</p>;
return (
<div>
{data.length > 0 &&
data.map((cdata) => {
return <ExpenseItem name={cdata.name}></ExpenseItem>;
})}
</div>
);
---- react style documents ----
- simply specify states and play with them inside any component!
<div className={`form-control ${!isValid ? "invalid" : ""}`}
- (some more stuff is there you can look into it you want to!!!)
---- Fragments, Portals, Refs ----
- Wrapper is a nice little trick to solve this problem! -- simple
- <React.Fragment> </React.Fragment>
- Portal is simply rendering your div somewhere else (You can read it in much deeper if you want)
- Ref could be used to connect html components! Hence you don't have to keep the state for that
const nameInputRef = useRef();
<input ref={nameInputRef} />
- input components become uncontrolled because their value is not controlled by react anymore!! Remember that
--- Advanced Handling ---
-- useEffect() --- (really cool!!!)
- Like - store data in browser, send http requests, set & manage intervals
useEffect(() => {}, [dependencies...])
localStorage.setItem("isLoggedIn", "1");
useEffect(() => {}, [dependencies...])
localStorage.setItem("isLoggedIn", "1");
- useEffect runs for the first time, and everytime its dependencies changes -- simple
- CLEAN UP FUNCTIONS RUNS BEFORE BEFORE BEFORE THE USE EFFECT FUNCTIONS RUNS -- except the first time it runs
useEffect(() => {
setTimeout(() => {
setNormal("random");
}, 500);
return () => {}; //this is the cleanup function
});
- some cool timeout and cleanTime stuff is used (If you are interested go deeper into it brother)
-- useReducer() --- (if you want to figure it out a bit more)
const [password, setPassword] = useReducer(emailReducer, initial_value);
- then you use dispatcher and stuff if you want -- (some really cool stuff is happening for sure)
-- useContextAPI() --- (important)
- this creates app wise state management which is pretty cool for sure
const ctx = useContext(AuthContext);
<AuthContext.Provider
value={{
isLoggedIn: true,
}}
>
</AuthContext>
-- creating this inside store folder for your use case only!
import React from "react";
const AuthContext = React.createContext({
isLoggedIn: false,
});
export default AuthContext;
- add other functions in here as well, for auto-completion
- You can create complete stuff inside auth-context, from setting up to state and writing functions
- and ofc use the above shit, view revision section and you would know how to do this if you want to in future
const AuthContextProvider = (props) => {
return (
<AuthContext.Provider
value={{
isLoggedIn: isLogged,
onLogout: logoutHandler,
}}
>
{props.children}
</AuthContext.Provider>
);
};
- react context is not optimised for high frequency changes
- redux is there for better stuff and all!!
-- Rules for HOOK ---
- (only call react hooks in react functions) - (react components , or custom hooks)
- only call react hooks at the top level - never inside a callback or any other function
- use props to make usable component!! Make reusable components brother
-- (STUDY ABOUT FORWARD REFS if you want to) -- in your free time for react and stuff
-- STUDY OPTIMSATION OF REACT AND STUFF IN FREE TIME if you want to!!
--- SENDING HTTP REQUESTS ---
- connecting to backend and database
npm install axios (one badass library used for multipurposes)
- this function should be inside some component for sure if you want to use it extensively brother
const getMovies = async () => {
- get data from here, and call that function, simple as that
setLoading(true);
try {
const response = await axios.get("https://swapi.dev/api/films");
addMoviesHandler(response.data.results);
} catch (err) {
console.log(err);
}
setLoading(false);
};
- you can show the loading spinner using setLoading state, as soon as you call the fetch api, simple start loading, pretty cool tho!!!
- throw new Error('some message'); and catch it and update the state
- and handle it using states, if some error happened, then it should be not null or something
- you can use useEffect correctly using some callback functions and shit (STUDY ABOUT IT IN MORE DEPTH IF YOU WANT)
- study about post request and stuff (STUDY YOU WILL NEED IT FOR AXIOS for sure!!!)
--- CUSTOM HOOKS ---
const useCounter = () => {
const [counter, setCounter] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCounter((prevCounter) => prevCounter + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return counter;
};
-- simple custom hooks which returns count which have these features, you are returning it using it anywhere you want
- you can customise custom hooks on the basis of what the props you are adding to them!!
- (try to exactly understand what the above function is doing basically)
- GOT IT, so basically useEffect only happens once, but this setInterval shit keeps happening again and again
- and once this component is unmounted, it will simply clear this timeout which is happening!! (pretty cool)
- YOU CAN LOOK INTO CUSTOM HTTP HOOKS IF YOU WANT TO!!! (or see how they are doing, whatever you like brother) -- custom hooks toh aagye samajh
- THE ABOVE SHIT COULD BE REALLY USEFUL FOR THE WEBSITE IF YOU THINK ABOUT IT!!! (not bad not bad!!)
- {method, headers, body} -- for post request maybe
- useCallback is dope ass shit!! (do get used to this brother, please)
--- ROUTING ---
- defining routes -- | first step |
npm install react-router-dom
- create pages folder and add Home component in there
const router = createBrowserRouter([
{ path: "/", element: <HomePage /> },
{ path: "/products", element: <ProductsPage /> },
]);
return <RouterProvider router={router} />;
- One more approach is there, which was used before 6.4 and stuff, if you want you can look into it (pretty similar)
- for navigating between the pages, this could be used
<Link to="/products">product page!</Link>
- parent element ke andar routees chle?? Wrapper for all routes, how to do that?
- Some dope level nesting routes!!
const router = createBrowserRouter([
{
path: "/",
element: <RootLayout />,
children: [
{ path: "/", element: <HomePage /> },
{ path: "/products", element: <ProductsPage /> },
],
},
]);
const RootLayout = () => {
return (
<div>
Hey there buddy
<div>
<Outlet />
</div>
</div>
);
};
- error pages and stuff
errorElement: <Error />,
- (NavLink study more deeper about if you want) - if you want you can add those in here bruh!
- programmatically navigate between pages, you can use
useNavigate() hook could be used
const navigate = useNavigate();
const changeNavigate = () => {
navigate("/products");
};
-- params --
{ path: "/products/:productId", element: <ProductDetail /> },
const params = useParams();
<p>{params.productId}</p>
<Link to="/products/product-1">Product 1</Link>
-- relative path and absolute paths!!
-- relative pathing is used in below stuff, otherwise normally its absolute path
const router = createBrowserRouter([
{
path: "/",
element: <RootLayout />,
errorElement: <Error />,
children: [
{ path: "", element: <HomePage /> },
{ path: "products", element: <ProductsPage /> },
{ path: "products/:productId", element: <ProductDetail /> },
],
},
]);
<Link to=".." relative="path"> (if you are facing some issues with path you can check this out) - relative and absolute paths differences, simple
-- index routes, default route -- simple
const router = createBrowserRouter([
{
path: "/",
element: <RootLayout />,
errorElement: <Error />,
children: [
{ index: true, element: <HomePage /> },
{ path: "products", element: <ProductsPage /> },
{ path: "products/:productId", element: <ProductDetail /> },
],
},
]);
--- useLoader ----
- basically loading data before going to that route, so you will have
the data way before reaching that route! -> Hence no time wasted in loading and stuff
- You can make loader inside the routes, make the async function and all
- all the routes at that level or below that level will be able to access that data using useLoaderData() hook
{ path: "products", element: <ProductsPage />, loader: ProductsLoader },
const events = useLoaderData();
export const loader = async () => {
try {
const response = await axios.get("http://localhost:8080/events");
console.log(response);
return response.data.events;
} catch (err) {
return "";
}
};
-- use setTimeout() feature to showcase delay and everything! (not so bad bruh!!)
- one you will click on that route, then only data will be first fetched
then that page will be loaded, good thing is we will have all the data once we reach there
downside being that we would have to wait sometimes if data fetching did take some time!!!
- useNavigation() hook can be used, to show different states on the current page!! (YOU CAN STUDY ABOUT IT IF YOU WANT TO)
- You can not use hooks in loader function!! (EVERYTHING ELSE -- yes)
if(data.isError) -- for checking if data has that property or not, simple
-- error handling using loader -- (works!)
export const loader = async () => {
try {
const response = await axios.get("http://localhost:8080/events");
if (!response.ok) {
throw { message: "could not fetch data" };
} else {
return response.data.events;
}
} catch (err) {
throw err;
}
};
- you can set errorElement inside routing, and it will take you there!
-> useRouteError, and Responses (YOU CAN STUDY IF YOU WANT TO)
-- JSON utility function --
json function automatically parse object to JSON format, while using these useRouteError and etc feature,
would have to go much deeper into it! But whatever bruh!
- so basically loaders can be dyanamic as well
loader({request, params}){
fetch("url" + params.eventId)
}
- Hence as you can see above, request and params are there whenever a loader function is created, you can use this
for making dynamic shit
- for the routes which does not have loader, they can access parent loaders using useRouterLoaderData() (IMPORTANT)
- Some id and shit have to be configured, look into it more if you want that!
-- SO Basically what I am getting is
- when we want to load data, we do all those lengthy and big ass steps, where as we could use loaders right?
- similary when we want to send the form data, we can use those double binding, ref, and what not! But there is a better option - action! (look into it)
-- you can handle FORM submission using action! (IF YOU WANT TO)
- some detailed steps are there, FORM component, redirect, request for data from from in action
- use json also if you want to! All upto you brother! -- think and work on it! (whichever you like)
- action="/asdjflada/alkfdj" (inside form can trigger action of some other route/componet!)
- while deleting something, you can pop up a window on browser (how cool is that)
const proceed = window.confirm("Are you sure?");
if(proceed){ //code }else{ //code }
- If you want to tell when to submit on the button click, you could use that feature
- useSubmit() -- and then submit({data}, {method : "delete"}) -- otherwise it was all happening and calling the button on the click of the button!! (think about it)
- Pragammatically is pretty cool!
- You can set submitting feedback button!! (not bad not bad) -- just using useNavigation for feedback and stuff
- when you will submit it, then at that moment useNavigation value will be changed and you can update shit for the small duration of time!!
- Validation can be done as well with action, basically is response is not what you want, you can useActionData() and update the UI of the page
- Pretty much validation from backend can be shown and shit!! (which would be pretty useful for sure!!) -- Action are pretty cool for real!!! (not gonna lie!)
- You can reuse action, by modifying the code to be reusable, and two people can use one action! (LOOK INTO IT IF YOU WANT TO)
- FETCHER is there ( --- YOU CAN LEARN MORE ABOUT IF YOU WANT TO BROTHER --- )
- DEFER (not in the mood to learn right now, check it out much later on!)
----- FORMS AND SUBMISSION -----
- till now best 2 ways were using ref or double binding!
- below code mention both of them cleanly!! look into it, and it's not ideal because we are manipulating the DOM and not react!!! (NOT IDEAL)
const FormsPractise = () => {
const nameInputRef = useRef();
const [enteredName, setEnteredName] = useState();
const updateNameHandler = (event) => {
setEnteredName(event.target.value);
};
const formSubmissionHandler = (event) => {
event.preventDefault();
const enteredValue = nameInputRef.current.value;
// nameInputRef.current.value = ""; ==> NOT IDEAL BROTHER!!
setEnteredName("");
};
return (
<form onSubmit={formSubmissionHandler}>
<div>
<label htmlFor="name"> Your name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={updateNameHandler}
value={enteredName}
/>
</div>
<div>
<button>Submit</button>
</div>
</form>
);
};
export default FormsPractise;
- You can add validation using these two (VALIDATION)
const [enteredName, setEnteredName] = useState();
const [enteredNameTouched, setEnteredNameTouched] = useState(false);
- methods
onBlur
onClick
- simply if you don't want anyone to click this button
<button disabled={true}>Submit</button>
- making use-input custom hook (and basically write less code, simple!)
MUI stuff
------ TYPOGRAPHY -----
- variant provided by MUI
- componenet we provided
- gutterBottom is margin below
<Typography variant='h1' component='h1' gutterBottom></Typography>
------ BUTTON -----
- want to grap less attention
<Button variant='text' color='primary'></Button>
- highest attention
<Button variant='contained'></Button>
- medium attention
<Button variant='outlined'></Button>
- using icons with buttons
<Stack spacing={2} direction='row'>
<Button startIcon={<random/>} ></Button>
<IconButton><SendIcon/></IconButton>
<Button></Button>
<Button></Button>
</Stack>
- some more properties regarding buttons
- disableElevation (set elevation on button)
- disableRipple (ripple effect is removed)
--- TOGGLE BUTTON ---
- complete process of how to set handlers on it as well! (pretty cool)
--- TextFields ---
<TextField label ="name" variant="outlined" />
<TextField label ="name" variant="filled" />
<TextField label ="name" variant="standard" required/>
<TextField label ="name" variant="standard" type='password' required/>
<TextField label ="name" variant="filled" helperText="add this"/>
----- SELECT component ----
look into the video
----- RADIO BUTTON ----
look in the video
----- CHECKBOX BUTTON ----
look in the video