-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreact.html
More file actions
771 lines (671 loc) · 27.4 KB
/
react.html
File metadata and controls
771 lines (671 loc) · 27.4 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React.js Comprehensive Cheatsheet</title>
<script src="https://cdn.tailwindcss.com"></script>
<style type="text/tailwindcss">
@layer utilities {
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
.code-block {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
}
.react-blue {
color: #61dafb;
}
}
</style>
</head>
<body class="bg-gray-100 text-gray-800">
<div class="container mx-auto px-4 py-8 max-w-6xl">
<header class="mb-12 text-center">
<h1 class="text-4xl font-bold react-blue mb-2">React.js Comprehensive Cheatsheet</h1>
<p class="text-lg text-gray-600">Everything you need to know to build React applications</p>
<div class="mt-6 flex flex-wrap justify-center gap-4">
<button onclick="filterContent('all')" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition">All</button>
<button onclick="filterContent('core')" class="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300 transition">Core Concepts</button>
<button onclick="filterContent('hooks')" class="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300 transition">Hooks</button>
<button onclick="filterContent('advanced')" class="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300 transition">Advanced</button>
<button onclick="filterContent('performance')" class="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300 transition">Performance</button>
</div>
</header>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- Core Concepts -->
<div class="core section bg-white rounded-lg shadow-md overflow-hidden">
<div class="bg-blue-600 text-white px-4 py-3">
<h2 class="text-xl font-semibold">Core Concepts</h2>
</div>
<div class="p-4">
<!-- JSX -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">JSX</h3>
<p class="text-gray-600 mb-3">JavaScript XML allows writing HTML-like syntax in JavaScript.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>// Basic JSX
const element = <h1>Hello, world!</h1>;
// Embedding expressions
const name = 'John';
const element = <h1>Hello, {name}</h1>;
// JSX is an expression too
function getGreeting(user) {
if (user) {
return <h1>Hello, {user.name}</h1>;
}
return <h1>Hello, Stranger</h1>;
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Note:</strong> JSX gets compiled to <code>React.createElement()</code> calls.</p>
</div>
<!-- Components -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">Components</h3>
<p class="text-gray-600 mb-3">Building blocks of React applications. Can be functions or classes.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>// Function Component (recommended)
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
// Class Component
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
// Using components
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
</div>
);
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Best Practice:</strong> Use function components with hooks for new code.</p>
</div>
<!-- Props -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">Props</h3>
<p class="text-gray-600 mb-3">Read-only data passed from parent to child components.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>// Passing props
function App() {
return <Welcome name="Sara" age={25} />;
}
// Accessing props (function component)
function Welcome(props) {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
</div>
);
}
// Accessing props (class component)
class Welcome extends React.Component {
render() {
return (
<div>
<p>Name: {this.props.name}</p>
<p>Age: {this.props.age}</p>
</div>
);
}
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Rule:</strong> Props are immutable - children shouldn't modify their props.</p>
</div>
<!-- State -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">State</h3>
<p class="text-gray-600 mb-3">Mutable data that affects component rendering.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>// Class component state
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
// Function component state (with hooks)
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Important:</strong> Never modify state directly, always use setState or the state setter function.</p>
</div>
</div>
</div>
<!-- Hooks Section -->
<div class="hooks section bg-white rounded-lg shadow-md overflow-hidden">
<div class="bg-purple-600 text-white px-4 py-3">
<h2 class="text-xl font-semibold">Hooks</h2>
</div>
<div class="p-4">
<!-- useState -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">useState</h3>
<p class="text-gray-600 mb-3">Adds state to function components.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>import { useState } from 'react';
function Counter() {
// Declare state variable 'count' with initial value 0
const [count, setCount] = useState(0);
// Functional updates for derived state
const increment = () => {
setCount(prevCount => prevCount + 1);
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={increment}>
Click me
</button>
</div>
);
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Tip:</strong> Use functional updates when new state depends on previous state.</p>
</div>
<!-- useEffect -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">useEffect</h3>
<p class="text-gray-600 mb-3">Handles side effects in function components.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate
useEffect(() => {
// Update the document title
document.title = `You clicked ${count} times`;
// Cleanup function (similar to componentWillUnmount)
return () => {
document.title = 'React App';
};
}, [count]); // Only re-run if count changes
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Patterns:</strong> Use empty dependency array [] for mount/unmount behavior, include dependencies to run when they change.</p>
</div>
<!-- useContext -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">useContext</h3>
<p class="text-gray-600 mb-3">Access context without wrapping in Consumer.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>import { createContext, useContext } from 'react';
// Create a context
const ThemeContext = createContext('light');
function App() {
return (
// Provide the context value
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return <ThemedButton />;
}
function ThemedButton() {
// Consume the context value
const theme = useContext(ThemeContext);
return <button className={theme}>Themed Button</button>;
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Use Case:</strong> Avoid prop drilling by sharing data across many components.</p>
</div>
<!-- useReducer -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">useReducer</h3>
<p class="text-gray-600 mb-3">Alternative to useState for complex state logic.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>import { useReducer } from 'react';
// Reducer function
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</div>
);
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>When to use:</strong> When state logic is complex or involves multiple sub-values.</p>
</div>
</div>
</div>
<!-- Advanced Section -->
<div class="advanced section bg-white rounded-lg shadow-md overflow-hidden">
<div class="bg-green-600 text-white px-4 py-3">
<h2 class="text-xl font-semibold">Advanced Patterns</h2>
</div>
<div class="p-4">
<!-- Refs -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">Refs</h3>
<p class="text-gray-600 mb-3">Access DOM nodes or persist values across renders.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>import { useRef, useEffect } from 'react';
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted input element
inputEl.current.focus();
};
return (
<div>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>
Focus the input
</button>
</div>
);
}
// Mutable value that doesn't trigger re-renders
function Timer() {
const intervalRef = useRef();
useEffect(() => {
intervalRef.current = setInterval(() => {
// ...
}, 1000);
return () => clearInterval(intervalRef.current);
}, []);
// ...
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Remember:</strong> Changing refs doesn't trigger re-renders.</p>
</div>
<!-- Custom Hooks -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">Custom Hooks</h3>
<p class="text-gray-600 mb-3">Extract component logic into reusable functions.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>import { useState, useEffect } from 'react';
// Custom hook for fetching data
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
}
// Using the custom hook
function UserProfile({ userId }) {
const { data: user, loading, error } = useFetch(
`https://api.example.com/users/${userId}`
);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>{user.name}</h1>
<p>Email: {user.email}</p>
</div>
);
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Convention:</strong> Custom hook names must start with "use".</p>
</div>
<!-- Context API -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">Context API</h3>
<p class="text-gray-600 mb-3">Share data across the component tree without prop drilling.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>import { createContext, useContext, useState } from 'react';
// Create a context
const UserContext = createContext();
function App() {
const [user, setUser] = useState({ name: 'John', age: 30 });
return (
// Provide the context value
<UserContext.Provider value={{ user, setUser }}>
<Navbar />
<MainContent />
</UserContext.Provider>
);
}
function Navbar() {
// Consume the context
const { user } = useContext(UserContext);
return (
<div>
<p>Welcome, {user.name}</p>
</div>
);
}
function MainContent() {
// Consume and update the context
const { user, setUser } = useContext(UserContext);
const updateName = () => {
setUser({ ...user, name: 'Jane' });
};
return (
<div>
<p>Age: {user.age}</p>
<button onClick={updateName}>Change Name</button>
</div>
);
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Best Practice:</strong> Split contexts for different concerns (theme, auth, etc.).</p>
</div>
<!-- Render Props -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">Render Props</h3>
<p class="text-gray-600 mb-3">Share code between components using a prop that's a function.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>// Component with render prop
class MouseTracker extends React.Component {
state = { x: 0, y: 0 };
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY
});
};
render() {
return (
<div onMouseMove={this.handleMouseMove}>
{this.props.render(this.state)}
</div>
);
}
}
// Using the component
function App() {
return (
<div>
<h1>Move the mouse around!</h1>
<MouseTracker render={({ x, y }) => (
<p>
The current mouse position is ({x}, {y})
</p>
)} />
</div>
);
}
// Children as function (alternative pattern)
function MouseTracker({ children }) {
// ... same state and handler
return (
<div onMouseMove={this.handleMouseMove}>
{children(this.state)}
</div>
);
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Alternative:</strong> Often replaced by custom hooks in modern React.</p>
</div>
</div>
</div>
<!-- Performance Section -->
<div class="performance section bg-white rounded-lg shadow-md overflow-hidden">
<div class="bg-yellow-600 text-white px-4 py-3">
<h2 class="text-xl font-semibold">Performance</h2>
</div>
<div class="p-4">
<!-- React.memo -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">React.memo</h3>
<p class="text-gray-600 mb-3">Prevent unnecessary re-renders of functional components.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>import { memo } from 'react';
const MyComponent = memo(function MyComponent(props) {
/* render using props */
});
// With custom comparison function
const MyComponent = memo(
function MyComponent(props) {
/* render using props */
},
(prevProps, nextProps) => {
/*
Return true if passing nextProps would return
the same result as passing prevProps,
otherwise return false
*/
return prevProps.value === nextProps.value;
}
);
// Example usage
function ParentComponent() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(c => c + 1)}>
Increment: {count}
</button>
<MemoizedChild value="static" />
</div>
);
}
const MemoizedChild = memo(function Child({ value }) {
console.log('Child rendered');
return <div>{value}</div>;
});</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Note:</strong> Only use when necessary - premature optimization can hurt performance.</p>
</div>
<!-- useMemo -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">useMemo</h3>
<p class="text-gray-600 mb-3">Memoize expensive calculations to avoid re-computation.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>import { useMemo } from 'react';
function ExpensiveComponent({ list, filter }) {
const filteredList = useMemo(() => {
return list.filter(item => item.includes(filter));
}, [list, filter]); // Only recompute when list or filter changes
return (
<ul>
{filteredList.map(item => (
<li key={item}>{item}</li>
))}
</ul>
);
}
// Another example with complex calculation
function Component({ a, b }) {
const result = useMemo(() => {
return complexCalculation(a, b);
}, [a, b]);
return <div>{result}</div>;
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>When to use:</strong> When the computation is significantly slower than the re-render itself.</p>
</div>
<!-- useCallback -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">useCallback</h3>
<p class="text-gray-600 mb-3">Memoize functions to prevent unnecessary re-creations.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>import { useCallback } from 'react';
function ParentComponent() {
const [count, setCount] = useState(0);
// Without useCallback - recreated on every render
const handleClick = () => {
console.log('Clicked');
};
// With useCallback - same function unless dependencies change
const memoizedHandleClick = useCallback(() => {
console.log('Clicked');
}, []); // No dependencies - never changes
// With dependency
const increment = useCallback(() => {
setCount(c => c + 1);
}, []); // setCount is stable so no dependencies needed
return (
<div>
<button onClick={increment}>Increment: {count}</button>
<ChildComponent onClick={memoizedHandleClick} />
</div>
);
}
const ChildComponent = memo(function Child({ onClick }) {
console.log('Child rendered');
return <button onClick={onClick}>Click me</button>;
});</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Use Case:</strong> Mostly useful when passing callbacks to optimized child components.</p>
</div>
<!-- Code Splitting -->
<div class="mb-6">
<h3 class="text-lg font-medium text-gray-800 mb-2">Code Splitting</h3>
<p class="text-gray-600 mb-3">Reduce bundle size by loading code only when needed.</p>
<div class="bg-gray-800 text-gray-100 p-3 rounded code-block text-sm overflow-x-auto scrollbar-hide">
<pre>// Using React.lazy and Suspense
import { lazy, Suspense } from 'react';
const OtherComponent = lazy(() => import('./OtherComponent'));
const AnotherComponent = lazy(() => import('./AnotherComponent'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<section>
<OtherComponent />
<AnotherComponent />
</section>
</Suspense>
</div>
);
}
// With React Router
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));
function App() {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
</Switch>
</Suspense>
</Router>
);
}</pre>
</div>
<p class="text-gray-600 mt-2 text-sm"><strong>Best Practice:</strong> Split routes and large components that aren't immediately needed.</p>
</div>
</div>
</div>
</div>
<footer class="mt-12 text-center text-gray-600 text-sm">
<p>React.js Comprehensive Cheatsheet - Updated for React 18</p>
<p class="mt-2">Includes core concepts, hooks, advanced patterns, and performance optimization</p>
</footer>
</div>
<script>
// Filter content based on category
function filterContent(category) {
const sections = document.querySelectorAll('.section');
// Update button styles
const buttons = document.querySelectorAll('header button');
buttons.forEach(button => {
if (button.textContent.toLowerCase().includes(category) ||
(category === 'all' && button.textContent === 'All')) {
button.classList.remove('bg-gray-200');
button.classList.add('bg-blue-600', 'text-white');
} else {
button.classList.remove('bg-blue-600', 'text-white');
button.classList.add('bg-gray-200');
}
});
// Show/hide sections
sections.forEach(section => {
if (category === 'all' || section.classList.contains(category)) {
section.style.display = 'block';
} else {
section.style.display = 'none';
}
});
}
// Copy code blocks to clipboard
document.addEventListener('DOMContentLoaded', function() {
const codeBlocks = document.querySelectorAll('.code-block pre');
codeBlocks.forEach(block => {
block.addEventListener('click', function() {
const range = document.createRange();
range.selectNode(block);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
try {
const successful = document.execCommand('copy');
const msg = successful ? 'Copied!' : 'Unable to copy';
const originalText = block.textContent;
// Show feedback
block.textContent = msg;
setTimeout(() => {
block.textContent = originalText;
}, 1000);
} catch (err) {
console.log('Oops, unable to copy');
}
window.getSelection().removeAllRanges();
});
// Add cursor pointer to indicate clickable
block.style.cursor = 'pointer';
});
});
</script>
</body>
</html>