Topic01 / 46
Introduction to React
What & Why
React is a JavaScript library for building user interfaces using a component-based model. It uses a Virtual DOM to efficiently update only the parts of the page that change — making it the most popular UI library and a must-have skill for frontend roles.
Syntax
jsx
1// React component (modern functional style)
2import React from 'react';
3
4function Greeting({ name, role = 'User' }) {
5 return (
6 <div className="greeting">
7 <h1>Hello, {name}! 👋</h1>
8 <p>Role: {role}</p>
9 </div>
10 );
11}
12
13export default Greeting;
14
15// Usage
16<Greeting name="Priya" role="Admin" />Real-World Example
A reusable UserAvatar component:
example.ts
jsx
1function UserAvatar({ user, size = 'md', showOnline = false }) {
2 const sizes = { sm: 32, md: 48, lg: 64 };
3
4 return (
5 <div className="avatar-wrapper" style={{ position: 'relative', display: 'inline-block' }}>
6 <img
7 src={user.avatarUrl ?? `https://api.dicebear.com/7.x/initials/svg?seed=${user.name}`}
8 alt={`${user.name}'s avatar`}
9 width={sizes[size]}
10 height={sizes[size]}
11 style={{ borderRadius: '50%' }}
12 />
13 {showOnline && user.isOnline && (
14 <span
15 className="online-dot"
16 aria-label="Online"
17 style={{
18 position: 'absolute', bottom: 2, right: 2,
19 width: 10, height: 10, borderRadius: '50%',
20 background: '#10B981', border: '2px solid #0f0f0f'
21 }}
22 />
23 )}
24 </div>
25 );
26}Pitfalls & Interview Tips
- ⚠️JSX is NOT HTML — use className (not class), htmlFor (not for), onClick (not onclick).
- ⚠️Components must return a single root element — wrap multiple elements in <> (Fragment) or a div.
- 💡Interview tip: The Virtual DOM is a lightweight copy of the real DOM. React diffs the virtual tree and applies minimal changes to the real DOM.