🎓 What You Will Learn
- JSX Syntax: Write HTML-like syntax in JavaScript
- Components: Create reusable, modular UI pieces
- Props: Pass data from parent to child components
- State: Manage dynamic data with
useState - Event Handling: Respond to user interactions
- Conditional Rendering: Show/hide elements based on conditions
- Lists & Keys: Render multiple items efficiently
- Forms: Handle user input and form submission
What is React?
React is a JavaScript library for building user interfaces. It makes building interactive web apps easier by breaking your UI into small, reusable pieces called components.
Think of React like LEGO: You build small blocks (components), then combine them to create bigger structures (apps).
JSX — JavaScript XML
JSX lets you write HTML-like code in JavaScript. It looks like HTML but it's actually JavaScript under the hood.
// JSX looks like HTML but it's JavaScript
const name = "Alice";
const element = <h1>Hello, {name}!</h1>;
// JSX gets converted to JavaScript function calls
// const element = React.createElement('h1', null, 'Hello, Alice!');- • One top-level element (wrap in
<div>or<></>) - • Use
classNameinstead ofclass - • Use
htmlForinstead offor - • Self-closing tags need
/(like<img />) - • Use curly braces
{}for JavaScript expressions
Hello React! 👋
This is rendered from JSX
Functional Components
A component is a JavaScript function that returns JSX. It's a reusable piece of UI.
// Functional Component (modern way)
export function Welcome() {
return (
<div>
<h1>Welcome to React!</h1>
<p>This is a functional component</p>
</div>
);
}
// Usage
function App() {
return <Welcome />;
}Props — Passing Data
Props (properties) let you pass data from a parent component to a child component. Props are like function parameters.
// Component that receives props
function Greeting({ name, emoji }) {
return <h1>{emoji} Hello, {name}!</h1>;
}
// Usage: Pass props as attributes
function App() {
return (
<>
<Greeting name="Alice" emoji="👋" />
<Greeting name="Bob" emoji="😊" />
<Greeting name="Charlie" emoji="🎉" />
</>
);
}Alice
Age: 28
Role: Developer
Bob
Age: 35
Role: Designer
Charlie
Age: 22
Role: Intern
State — Dynamic Data
State is data that can change. Use the useState hook to add state to functional components.
import { useState } from 'react';
export function Counter() {
// useState returns [currentValue, functionToUpdate]
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}count++ ✅ setCount(count + 1)Count: 0
Message: Hello!
Conditional Rendering
Show or hide elements based on conditions using if statements, ternary operators, or logical AND.
{isLoggedIn ? (
<p>Welcome back!</p>
) : (
<p>Please log in</p>
)}{isAdmin && <button>Delete User</button>}
{isLoading && <p>Loading...</p>}Please log in to continue
You are a teenager 👦
Event Handling
Handle user interactions like clicks, form submissions, and input changes.
export function EventDemo() {
const [count, setCount] = useState(0);
// Click handler
const handleClick = () => {
setCount(count + 1);
};
// Form submission
const handleSubmit = (e) => {
e.preventDefault(); // Prevent page reload
console.log("Form submitted!");
};
return (
<>
<button onClick={handleClick}>Click me</button>
<form onSubmit={handleSubmit}>
<input type="text" />
<button type="submit">Submit</button>
</form>
</>
);
}| Event | Handler | Example |
|---|---|---|
| Click | onClick | <button onClick={handleClick}> |
| Input Change | onChange | <input onChange={(e) => ...} |
| Form Submit | onSubmit | <form onSubmit={handleSubmit}> |
| Mouse Enter | onMouseEnter | <div onMouseEnter={...}> |
| Key Press | onKeyPress | <input onKeyPress={...} |
The Children Prop
children is a special prop that contains anything passed between component tags.
// Component definition
function Card({ title, children }) {
return (
<div>
<h2>{title}</h2>
{children}
</div>
);
}
// Usage: content between tags becomes children
function App() {
return (
<Card title="My Card">
<p>This content is passed as children</p>
</Card>
);
}Welcome
👋 This is card content passed as children
Features
- Reusable components
- Flexible layouts
- Clean code
Code Snippet
const Component = ({ children }) => childrenCommon Patterns
function Button({ text = "Click me", color = "blue" }) {
return <button style={{ background: color }}>{text}</button>;
}
// Usage: Props are optional
<Button /> // Uses defaults
<Button text="Submit" color="green" /> // Custom propsconst [formData, setFormData] = useState({
name: "",
email: "",
message: ""
});
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
// Send to server...
};const [isOpen, setIsOpen] = useState(false);
return (
<>
<button onClick={() => setIsOpen(!isOpen)}>
{isOpen ? "Close" : "Open"}
</button>
{isOpen && <div>Content is visible</div>}
</>
);React Hooks Overview
Hooks are special functions that let you "hook into" React features. The most common hooks are:
| Hook | Purpose | Example |
|---|---|---|
| useState | Add state to components | const [count, setCount] = useState(0) |
| useEffect | Side effects & cleanup | useEffect(() => {...}, []) |
| useContext | Global state | const theme = useContext(ThemeContext) |
| useReducer | Complex state logic | const [state, dispatch] = useReducer(...) |
| useRef | Direct DOM access | const inputRef = useRef() |
Best Practices
Quick Reference Table
| Concept | Example | When to Use |
|---|---|---|
| useState | const [x, setX] = useState(0) | Component's own data |
| Props | <Card title="..."> | Pass data to child |
| onClick | <button onClick={...}> | Handle clicks |
| onChange | <input onChange={...}> | Handle input changes |
| Ternary | {x ? <A /> : <B />} | Show/hide based on condition |
| Logical AND | {x && <B />} | Show only if true |
| .map() | {items.map(item => ...)} | Render lists |
| children | <Card>{content}</Card> | Pass content to component |
Common Mistakes to Avoid
// WRONG
count += 1;
setCount(count);
// RIGHT
setCount(count + 1);// WRONG
if (someCondition) {
const [state, setState] = useState(0);
}
// RIGHT: Always call hooks at top level
const [state, setState] = useState(0);// WRONG
{items.map((item, index) => (
<li key={index}>{item}</li> // Index keys are bad
))}
// RIGHT
{items.map(item => (
<li key={item.id}>{item.name}</li> // Use unique ID
))}What's Next?
- 1. React Lists: Render and manipulate lists dynamically
- 2. React Hooks: useEffect, useContext, useReducer, Custom Hooks
- 3. API Integration: Fetch data from servers with useEffect
- 4. Component Patterns: Higher-Order Components, Render Props, Custom Hooks
- 5. State Management: Context API, Redux, Zustand for complex apps
- 6. Testing: React Testing Library, Jest for reliable code
- 7. Performance: React.memo, Code Splitting, Lazy Loading
Build projects! 🚀 The best way to learn React is by building real apps. Start small (todo list, weather app) and gradually increase complexity!