-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathreact_tutorial.html
More file actions
828 lines (807 loc) · 34.8 KB
/
react_tutorial.html
File metadata and controls
828 lines (807 loc) · 34.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React.js Interview Questions</title>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
/* Original styles unchanged */
body {
font-family: 'Arial', sans-serif;
background: #f4f4f4;
margin: 0;
padding: 0;
transition: 0.3s;
}
.dark-mode {
background: #222;
color: #fff;
}
header {
background: #2c3e50;
color: #fff;
padding: 10px 20px;
display: flex;
justify-content: space-between;
align-items: center;
position: sticky;
top: 0;
z-index: 1000;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.logo {
font-size: 24px;
font-weight: bold;
color: #fff;
}
nav ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
align-items: center;
}
nav ul li {
margin-left: 25px;
}
nav ul li a {
color: #fff;
text-decoration: none;
font-weight: bold;
font-size: 16px;
transition: color 0.3s ease;
}
nav ul li a:hover {
color: #ff6f61;
}
.hamburger {
display: none;
font-size: 24px;
cursor: pointer;
}
.container {
max-width: 900px;
margin: 20px auto;
padding: 20px;
background: #fff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.dark-mode .container {
background: #333;
box-shadow: 0 4px 8px rgba(255, 255, 255, 0.2);
}
h1 {
text-align: center;
color: #007bff;
}
.search-box {
padding: 10px;
width: 80%;
max-width: 400px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
margin: 20px auto;
display: block;
}
.toggle-btn {
background: #008CBA;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
margin: 10px auto;
display: block;
transition: background 0.3s ease;
}
.toggle-btn:hover {
background: #005f73;
}
.section {
background: #f9f9f9;
padding: 15px;
margin: 10px 0;
border-radius: 10px;
cursor: pointer;
border-left: 5px solid #007bff;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.section:hover {
transform: translateY(-5px);
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}
.content {
display: none;
padding: 15px;
background: #fff;
border-left: 5px solid #007bff;
color: black;
margin: 10px 0;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.dark-mode .content {
background: #444;
color: white;
border-left: 5px solid #008CBA;
}
pre {
background: #1e1e1e;
color: lime;
padding: 15px;
border-radius: 5px;
overflow-x: auto;
position: relative;
}
.copy-btn {
position: absolute;
top: 10px;
right: 10px;
background: #007bff;
color: white;
border: none;
padding: 5px 10px;
border-radius: 3px;
cursor: pointer;
transition: background 0.3s ease;
}
.copy-btn:hover {
background: #0056b3;
}
textarea {
width: 100%;
height: 100px;
font-family: monospace;
margin-top: 10px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 14px;
}
.run-btn {
color: white;
padding: 8px 16px;
border: none;
border-radius: 5px;
cursor: pointer;
margin-right: 10px;
transition: background 0.3s ease;
}
.run-btn:hover {
background: #218838;
}
a {
display: block;
text-align: center;
margin-top: 20px;
color: white;
text-decoration: none;
border-radius: 5px;
transition: background 0.3s ease;
}
a:hover {
background: #0056b3;
}
footer {
background: #1a252f;
color: #fff;
text-align: center;
padding: 20px;
margin-top: 20px;
}
footer p {
margin: 0;
}
@media (max-width: 768px) {
.hamburger {
display: block;
}
nav ul {
display: none;
flex-direction: column;
width: 100%;
background: #2c3e50;
position: absolute;
top: 60px;
left: 0;
}
nav ul.active {
display: flex;
}
nav ul li {
margin: 10px 0;
text-align: center;
}
.header h3 {
font-size: 24px;
}
.search-box {
width: 90%;
}
.run-btn {
background: #000;
}
}
</style>
</head>
<body>
<!-- Header -->
<header>
<div class="logo">Learn Coding</div>
<nav>
<ul class="menu">
<li><a href="#home">Home</a></li>
<li><a href="#tutorials">Tutorials</a></li>
<li><a href="#topics">Topics</a></li>
<li><a href="#testimonials">Testimonials</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
<div class="hamburger" onclick="toggleMenu()">☰</div>
</nav>
</header>
<!-- Main Content -->
<div class="container">
<h1>Top 30 React.js Interview Questions</h1>
<input type="text" id="search" class="search-box" placeholder="🔍 Search topics..." onkeyup="searchTopics()">
<button class="toggle-btn" onclick="toggleDarkMode()">🌙 Toggle Dark Mode</button>
<button class="toggle-btn" onclick="showRandomQuestion()">🎲 Random Question</button>
<button class="toggle-btn" onclick="exportQuestions()">💾 Export Questions</button>
<div id="topics-container"></div>
</div>
<!-- Footer -->
<footer id="contact">
<p>© 2023 Learn Coding. All rights reserved.</p>
</footer>
<script>
const topics = [
["What is React?",
`React is an open-source JavaScript library developed by Facebook for building user interfaces, particularly for single-page applications. It allows developers to create reusable UI components that manage their own state, making it easier to build interactive and dynamic web applications. React uses a component-based architecture, enabling developers to break down complex UIs into smaller, manageable pieces. It is highly performant due to its use of the Virtual DOM, which minimizes direct manipulation of the actual DOM. React is widely used for its simplicity, flexibility, and strong community support.
<br><br><strong>Example:</strong><br>
<pre>
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => <h1>Hello, React!</h1>;
ReactDOM.render(<App />, document.getElementById('root'));
</pre>
This code renders a simple "Hello, React!" heading to the DOM.`],
["What are Components in React?",
`Components are the building blocks of a React application, representing reusable pieces of the UI. They can be either <strong>class-based</strong> (using ES6 classes) or <strong>functional</strong> (using functions). Components accept inputs called <strong>props</strong> and manage their own <strong>state</strong> to render dynamic UI. Functional components are preferred in modern React, especially with Hooks for state and side effects. Components promote modularity and reusability, making code easier to maintain.
<br><br><strong>Example:</strong><br>
<pre>
import React from 'react';
const Greeting = ({ name }) => <h1>Hello, {name}!</h1>;
export default Greeting;
</pre>
This functional component accepts a 'name' prop and renders a greeting.`],
["What is JSX?",
`JSX (JavaScript XML) is a syntax extension for JavaScript that allows developers to write HTML-like code within JavaScript. It makes React code more readable by combining UI structure with logic. JSX is transpiled by tools like Babel into plain JavaScript (React.createElement calls). It supports embedding JavaScript expressions using curly braces {} and allows attributes like HTML.
<br><br><strong>Example:</strong><br>
<pre>
const element = <h1>Hello, {user.name}!</h1>;
</pre>
This JSX renders an h1 element with a dynamic user name.`],
["What is State in React?",
`State is an object that holds dynamic data in a React component, allowing it to update and re-render when the data changes. State is managed within a component (or via state management libraries like Redux). In functional components, the <strong>useState</strong> Hook is used to manage state. State changes trigger re-renders, making the UI reactive.
<br><br><strong>Example:</strong><br>
<pre>
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
</pre>
This component tracks and updates a counter using state.`],
["What are Props?",
`Props (short for properties) are read-only inputs passed to React components to customize their behavior or output. They allow data to flow from parent to child components, enabling reusability. Props can include primitive values, objects, or functions.
<br><br><strong>Example:</strong><br>
<pre>
const Welcome = (props) => <h1>Hello, {props.name}!</h1>;
const App = () => <Welcome name="Alice" />;
</pre>
The Welcome component receives the 'name' prop and displays it.`],
["What is the Virtual DOM?",
`The Virtual DOM is a lightweight, in-memory representation of the actual DOM. React uses it to optimize updates by comparing the Virtual DOM with the previous version (diffing) and applying only the necessary changes to the real DOM. This minimizes expensive DOM operations, improving performance.
<br><br><strong>Example:</strong><br>
When a component's state changes, React updates the Virtual DOM, calculates the differences, and applies minimal updates to the real DOM.`],
["What is useEffect?",
`The <strong>useEffect</strong> Hook allows functional components to perform side effects, such as fetching data, updating the DOM, or setting up subscriptions. It runs after every render by default but can be controlled with a dependency array to run only when specific values change.
<br><br><strong>Example:</strong><br>
<pre>
import React, { useState, useEffect } from 'react';
const DataFetcher = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.example.com/data')
.then(res => res.json())
.then(setData);
}, []); // Empty array means run once on mount
return <div>{data.map(item => <p>{item.name}</p>)}</div>;
};
</pre>
This fetches data on component mount.`],
["What is React Router?",
`React Router is a library for handling navigation and routing in React applications. It enables dynamic, client-side routing, allowing users to navigate between different views without full page reloads. Key components include <strong>BrowserRouter</strong>, <strong>Route</strong>, and <strong>Link</strong>.
<br><br><strong>Example:</strong><br>
<pre>
import { BrowserRouter, Route, Link } from 'react-router-dom';
const App = () => (
<BrowserRouter>
<nav><Link to="/home">Home</Link></nav>
<Route path="/home" component={() => <h1>Home Page</h1>} />
</BrowserRouter>
);
</pre>
This sets up basic routing with a link to a home page.`],
["What are React Hooks?",
`React Hooks are functions that let functional components use state, lifecycle methods, and other React features without classes. Introduced in React 16.8, Hooks like <strong>useState</strong>, <strong>useEffect</strong>, and <strong>useContext</strong> simplify code and improve reusability.
<br><br><strong>Example:</strong><br>
<pre>
import React, { useState } from 'react';
const Toggle = () => {
const [isOn, setIsOn] = useState(false);
return <button onClick={() => setIsOn(!isOn)}>{isOn ? 'On' : 'Off'}</button>;
};
</pre>
This uses useState to toggle a button's state.`],
["What is useRef?",
`The <strong>useRef</strong> Hook creates a mutable reference that persists across renders without triggering re-renders. It’s commonly used to access DOM elements or store values that don’t affect the UI.
<br><br><strong>Example:</strong><br>
<pre>
import React, { useRef } from 'react';
const FocusInput = () => {
const inputRef = useRef(null);
const focus = () => inputRef.current.focus();
return (
<div>
<input ref={inputRef} />
<button onClick={focus}>Focus Input</button>
</div>
);
};
</pre>
This focuses an input field using useRef.`],
["What is Context API?",
`The Context API allows global state management in React by sharing data across components without prop drilling. It consists of a <strong>Provider</strong> to supply data and a <strong>Consumer</strong> (or <strong>useContext</strong> Hook) to access it.
<br><br><strong>Example:</strong><br>
<pre>
import React, { createContext, useContext } from 'react';
const ThemeContext = createContext();
const App = () => (
<ThemeContext.Provider value="dark">
<Child />
</ThemeContext.Provider>
);
const Child = () => {
const theme = useContext(ThemeContext);
return <p>Theme: {theme}</p>;
};
</pre>
This shares a theme value across components.`],
["What is memoization in React?",
`Memoization optimizes performance by caching the results of expensive computations or preventing unnecessary re-renders. In React, it’s achieved using <strong>React.memo</strong>, <strong>useMemo</strong>, and <strong>useCallback</strong>.
<br><br><strong>Example:</strong><br>
<pre>
import React, { useMemo } from 'react';
const ExpensiveComponent = ({ numbers }) => {
const sum = useMemo(() => numbers.reduce((a, b) => a + b, 0), [numbers]);
return <p>Sum: {sum}</p>;
};
</pre>
This caches the sum of numbers until the input changes.`],
["What are controlled and uncontrolled components?",
`A <strong>controlled component</strong> has its value managed by React state, making it predictable and easier to validate. An <strong>uncontrolled component</strong> relies on the DOM for its value, using refs to access it.
<br><br><strong>Example (Controlled):</strong><br>
<pre>
import React, { useState } from 'react';
const ControlledInput = () => {
const [value, setValue] = useState('');
return <input value={value} onChange={e => setValue(e.target.value)} />;
};
</pre>
<strong>Example (Uncontrolled):</strong><br>
<pre>
import React, { useRef } from 'react';
const UncontrolledInput = () => {
const inputRef = useRef();
return <input ref={inputRef} />;
};
</pre>`],
["What is lazy loading in React?",
`Lazy loading defers loading of components until they’re needed, improving initial load time and performance. React’s <strong>React.lazy</strong> and <strong>Suspense</strong> enable this.
<br><br><strong>Example:</strong><br>
<pre>
import React, { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
const App = () => (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
</pre>
This loads LazyComponent only when rendered.`],
["How to implement dark mode in React?",
`Dark mode toggles between light and dark themes, typically using CSS classes or variables and React state or Context API to manage the theme state.
<br><br><strong>Example:</strong><br>
<pre>
import React, { useState } from 'react';
const App = () => {
const [theme, setTheme] = useState('light');
return (
<div className={theme}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</div>
);
};
</pre>
CSS: .light { background: white; } .dark { background: black; color: white; }`],
["What is Redux and why is it used?",
`Redux is a predictable state management library for JavaScript apps, often used with React for managing global state in large applications. It centralizes state in a single store, using actions and reducers to update it.
<br><br><strong>Example:</strong><br>
<pre>
import { createStore } from 'redux';
const reducer = (state = { count: 0 }, action) => {
switch (action.type) {
case 'INCREMENT': return { count: state.count + 1 };
default: return state;
}
};
const store = createStore(reducer);
store.dispatch({ type: 'INCREMENT' });
</pre>
This increments a counter in the Redux store.`],
["What is React.memo?",
`React.memo is a higher-order component that memoizes functional components, preventing re-renders unless props change. It’s useful for optimizing performance in components with expensive renders.
<br><br><strong>Example:</strong><br>
<pre>
import React, { memo } from 'react';
const Child = memo(({ value }) => <p>{value}</p>);
</pre>
This prevents Child from re-rendering if 'value' is unchanged.`],
["What is useCallback and useMemo?",
`<strong>useCallback</strong> memoizes functions to prevent recreation on each render, while <strong>useMemo</strong> memoizes computed values. Both optimize performance by reducing unnecessary work.
<br><br><strong>Example (useCallback):</strong><br>
<pre>
import React, { useCallback } from 'react';
const Button = ({ onClick }) => <button onClick={onClick}>Click</button>;
const Parent = () => {
const handleClick = useCallback(() => console.log('Clicked'), []);
return <Button onClick={handleClick} />;
};
</pre>
<strong>Example (useMemo):</strong><br>
<pre>
import React, { useMemo } from 'react';
const Component = ({ numbers }) => {
const total = useMemo(() => numbers.reduce((a, b) => a + b, 0), [numbers]);
return <p>Total: {total}</p>;
};
</pre>`],
["What is Server-Side Rendering (SSR) in React?",
`Server-Side Rendering (SSR) renders React components on the server, sending fully formed HTML to the client. This improves SEO and initial load performance. Frameworks like Next.js simplify SSR.
<br><br><strong>Example (Next.js):</strong><br>
<pre>
export async function getServerSideProps() {
const data = await fetch('https://api.example.com/data').then(res => res.json());
return { props: { data } };
}
const Page = ({ data }) => <div>{data.map(item => <p>{item.name}</p>)}</div>;
export default Page;
</pre>
This fetches data on the server and renders it.`],
["What is Suspense in React?",
`Suspense allows components to "wait" for asynchronous operations (e.g., data fetching or lazy loading) while showing a fallback UI. It’s commonly used with <strong>React.lazy</strong>.
<br><br><strong>Example:</strong><br>
<pre>
import React, { Suspense, lazy } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
const App = () => (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
</pre>
This shows a loading message while LazyComponent loads.`],
["What is React Context API?",
`The Context API manages global state without prop drilling, using a Provider to supply data and Consumers (or useContext) to access it. It’s ideal for themes, user data, or other global values.
<br><br><strong>Example:</strong><br>
<pre>
import React, { createContext, useContext } from 'react';
const UserContext = createContext();
const App = () => (
<UserContext.Provider value={{ name: 'Alice' }}>
<User />
</UserContext.Provider>
);
const User = () => {
const user = useContext(UserContext);
return <p>User: {user.name}</p>;
};
</pre>`],
["What is React Router?",
`React Router manages navigation in React apps, enabling client-side routing. It uses components like <strong>BrowserRouter</strong>, <strong>Route</strong>, and <strong>Link</strong> to handle page transitions.
<br><br><strong>Example:</strong><br>
<pre>
import { BrowserRouter, Route, Link } from 'react-router-dom';
const App = () => (
<BrowserRouter>
<nav><Link to="/about">About</Link></nav>
<Route path="/about" component={() => <h1>About Page</h1>} />
</BrowserRouter>
);
</pre>`],
["What is Prop Drilling?",
`Prop drilling occurs when props are passed through multiple component layers to reach a deeply nested component, making code cumbersome. Context API or Redux can avoid this.
<br><br><strong>Example:</strong><br>
<pre>
const Grandchild = ({ data }) => <p>{data}</p>;
const Child = ({ data }) => <Grandchild data={data} />;
const Parent = () => <Child data="Hello" />;
</pre>
Here, 'data' is passed through Child to Grandchild unnecessarily.`],
["What are Controlled vs Uncontrolled Components?",
`Controlled components have their form data managed by React state, ensuring predictable behavior. Uncontrolled components store data in the DOM, accessed via refs.
<br><br><strong>Example (Controlled):</strong><br>
<pre>
import React, { useState } from 'react';
const Form = () => {
const [value, setValue] = useState('');
return <input value={value} onChange={e => setValue(e.target.value)} />;
};
</pre>
<strong>Example (Uncontrolled):</strong><br>
<pre>
import React, { useRef } from 'react';
const Form = () => {
const inputRef = useRef();
return <input ref={inputRef} />;
};
</pre>`],
["What is React Portals?",
`React Portals allow rendering components outside their parent DOM hierarchy, useful for modals or popups. They use <strong>ReactDOM.createPortal</strong>.
<br><br><strong>Example:</strong><br>
<pre>
import ReactDOM from 'react-dom';
const Modal = ({ children }) => ReactDOM.createPortal(
<div className="modal">{children}</div>,
document.getElementById('modal-root')
);
</pre>
This renders a modal outside the main DOM tree.`],
["What is the difference between useEffect and useLayoutEffect?",
`<strong>useEffect</strong> runs asynchronously after rendering, suitable for most side effects. <strong>useLayoutEffect</strong> runs synchronously before the browser paints, useful for DOM measurements.
<br><br><strong>Example (useLayoutEffect):</strong><br>
<pre>
import React, { useLayoutEffect, useRef } from 'react';
const Component = () => {
const divRef = useRef();
useLayoutEffect(() => {
console.log(divRef.current.getBoundingClientRect());
}, []);
return <div ref={divRef}>Measure me</div>;
};
</pre>`],
["What is React.lazy?",
`<strong>React.lazy</strong> enables lazy loading of components, reducing initial bundle size. It works with <strong>Suspense</strong> to show a fallback while loading.
<br><br><strong>Example:</strong><br>
<pre>
import React, { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
const App = () => (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
</pre>`],
["What is React.Fragment?",
`React.Fragment groups multiple elements without adding extra DOM nodes, keeping the DOM clean. It’s shorthand is <>...</>.
<br><br><strong>Example:</strong><br>
<pre>
import React from 'react';
const List = () => (
<>
<li>Item 1</li>
<li>Item 2</li>
</>
);
</pre>
This renders two list items without a wrapper div.`],
["What is Concurrent Mode in React?",
`Concurrent Mode is a set of React features that improve app responsiveness by allowing React to interrupt and prioritize rendering tasks. It’s useful for handling complex UIs with smooth updates.
<br><br><strong>Example:</strong><br>
Concurrent Mode is experimental and not fully implemented in the provided code, but it’s enabled in React 18 with <strong>createRoot</strong>.
<pre>
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
</pre>`]
];
const menuData = [
{
title: "Basic Math",
subMenu: [
{ name: "Trigonometry", link: "Trigonometry" },
{ name: "Algebra", link: "Algebra" },
{ name: "Geometry", link: "Geometry" },
]
},
{
title: "Tutorial",
subMenu: [
{ name: "React.js Tutorial", link: "react_tutorial" },
{ name: "Node.js Tutorial", link: "node_tutorial" },
{ name: "JavaScript Tutorial", link: "JavaScript_tutorial" }
]
}
];
const menuContainer = document.querySelector('.menu');
menuData.forEach(menuItem => {
const li = document.createElement('li');
const a = document.createElement('a');
a.href = `#${menuItem.title.toLowerCase()}`;
a.textContent = menuItem.title;
const subMenu = document.createElement('ul');
subMenu.classList.add('sub-menu');
menuItem.subMenu.forEach(subItem => {
subMenu.innerHTML += `<li><a href="${subItem.link}">${subItem.name}</a></li>`;
});
li.appendChild(a);
li.appendChild(subMenu);
menuContainer.appendChild(li);
});
// Initialize bookmarked and viewed questions from localStorage
let bookmarkedQuestions = JSON.parse(localStorage.getItem('bookmarkedQuestions')) || [];
let viewedQuestions = JSON.parse(localStorage.getItem('viewedQuestions')) || [];
let sectionStates = JSON.parse(localStorage.getItem('sectionStates')) || {};
// Render topics with bookmark and viewed indicators
const topicsContainer = document.getElementById('topics-container');
topics.forEach((topic, index) => {
const isBookmarked = bookmarkedQuestions.includes(index);
const isViewed = viewedQuestions.includes(index);
topicsContainer.innerHTML += `
<div class="section" onclick="toggleContent('q${index + 1}', ${index})">
<h2>
${index + 1}️⃣ ${topic[0]}
${isBookmarked ? '<span style="color: gold;">⭐</span>' : ''}
${isViewed ? '<span style="color: green;">✔</span>' : ''}
</h2>
<button class="copy-btn" onclick="bookmarkQuestion(${index}); event.stopPropagation();">
${isBookmarked ? 'Remove Bookmark' : 'Bookmark'}
</button>
</div>
<div id="q${index + 1}" class="content">
<p>${topic[1]}</p>
<textarea id="code${index + 1}">${topic[1]}</textarea><br>
<button class="run-btn" onclick="runCode('code${index + 1}')">Run</button>
<button class="copy-btn" onclick="copyToClipboard('code${index + 1}')">Copy</button>
</div>
`;
});
// Restore section states
Object.keys(sectionStates).forEach(id => {
const content = document.getElementById(id);
if (content && sectionStates[id]) {
content.style.display = 'block';
}
});
function toggleContent(id, index) {
let content = document.getElementById(id);
content.style.display = (content.style.display === 'none' || content.style.display === '') ? 'block' : 'none';
sectionStates[id] = content.style.display === 'block';
localStorage.setItem('sectionStates', JSON.stringify(sectionStates));
// Mark question as viewed
if (!viewedQuestions.includes(index)) {
viewedQuestions.push(index);
localStorage.setItem('viewedQuestions', JSON.stringify(viewedQuestions));
updateSectionIndicators(index);
}
}
function bookmarkQuestion(index) {
if (bookmarkedQuestions.includes(index)) {
bookmarkedQuestions = bookmarkedQuestions.filter(i => i !== index);
Swal.fire('Bookmark removed!');
} else {
bookmarkedQuestions.push(index);
Swal.fire('Question bookmarked!');
}
localStorage.setItem('bookmarkedQuestions', JSON.stringify(bookmarkedQuestions));
updateSectionIndicators(index);
}
function updateSectionIndicators(index) {
const section = document.getElementsByClassName('section')[index];
const isBookmarked = bookmarkedQuestions.includes(index);
const isViewed = viewedQuestions.includes(index);
section.querySelector('h2').innerHTML = `
${index + 1}️⃣ ${topics[index][0]}
${isBookmarked ? '<span style="color: gold;">⭐</span>' : ''}
${isViewed ? '<span style="color: green;">✔</span>' : ''}
`;
section.querySelector('.copy-btn').textContent = isBookmarked ? 'Remove Bookmark' : 'Bookmark';
}
function toggleDarkMode() {
document.body.classList.toggle('dark-mode');
Swal.fire('🌙 Dark mode ' + (document.body.classList.contains('dark-mode') ? 'enabled' : 'disabled'));
localStorage.setItem('darkMode', document.body.classList.contains('dark-mode'));
}
function searchTopics() {
let input = document.getElementById('search').value.toLowerCase();
let sections = document.getElementsByClassName('section');
for (let section of sections) {
section.style.display = section.textContent.toLowerCase().includes(input) ? '' : 'none';
}
}
function copyToClipboard(codeId) {
let codeElement = document.getElementById(codeId);
codeElement.select();
document.execCommand('copy');
Swal.fire('✅ Code copied!');
}
function runCode(codeId) {
let code = document.getElementById(codeId).value;
try {
eval(code);
} catch (error) {
Swal.fire('❌ Error: ' + error.message);
}
}
function showRandomQuestion() {
const randomIndex = Math.floor(Math.random() * topics.length);
const sections = document.getElementsByClassName('section');
for (let section of sections) {
section.style.display = 'none';
}
sections[randomIndex].style.display = '';
toggleContent(`q${randomIndex + 1}`, randomIndex);
Swal.fire(`Showing Question ${randomIndex + 1}`);
}
function exportQuestions() {
const data = topics.map(([question, answer]) => ({ question, answer }));
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'react_interview_questions.json';
a.click();
URL.revokeObjectURL(url);
Swal.fire('Questions exported as JSON!');
}
function toggleMenu() {
const menu = document.querySelector('.menu');
menu.classList.toggle('active');
}
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key === 'd') {
e.preventDefault();
toggleDarkMode();
}
if (e.ctrlKey && e.key === 's') {
e.preventDefault();
document.getElementById('search').focus();
}
if (e.ctrlKey && e.key === 'r') {
e.preventDefault();
showRandomQuestion();
}
if (e.ctrlKey && e.key === 'e') {
e.preventDefault();
exportQuestions();
}
});
// Restore dark mode preference
if (localStorage.getItem('darkMode') === 'true') {
document.body.classList.add('dark-mode');
}
</script>
</body>
</html>