you’re new to React, this post will walk you through all the fundamentals you need to get started.
We’ll cover:
✔ What React is
✔ Components
✔ JSX
✔ Props & State
✔ Event Handling
✔ Conditional Rendering
✔ Lists & Keys
✔ A small demo Todo App
By the end, you’ll have a solid foundation to start building apps in React 🚀.
1. ⚛️ What is React?
Definition
React is a JavaScript library for building user interfaces.
It was developed by Facebook (Meta) and is widely used to build dynamic, fast, and interactive web applications.
Explanation
- Traditional web apps: You manually update the DOM.
- React apps: React uses a virtual DOM → it calculates the minimal changes needed and updates the real DOM efficiently.
Key Features
- Component-based → Build UI as small reusable blocks
- Declarative → You describe what the UI should look like
- One-way data flow → Data flows from parent → child via props
Minimal React Starter (using CDN)
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>React 18 Starter</title>
</head>
<body>
<div id="root"></div>
<!-- React 18 + ReactDOM 18 -->
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<!-- Babel for JSX (dev only) -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
const { createRoot } = ReactDOM;
function App() {
return <h1>Hello React 👋</h1>;
}
const root = createRoot(document.getElementById('root'));
root.render(<App />);
</script>
</body>
</html>
2. 🧩 Components
Definition
A component is a reusable piece of UI (button, card, navbar).
Components return JSX and can accept props + manage their own state.
Functional Component (modern way)
function Hello({ name }) {
return <h2>Hello, {name}!</h2>;
}
// Usage
<Hello name="Tushar" />
Class Component (older way)
class HelloClass extends React.Component {
render() {
return <h2>Hello, {this.props.name}!</h2>;
}
}
// Usage
<HelloClass name="Tushar" />
👉 Use functional components with hooks in modern React.
3. ✨ JSX Syntax
Definition
JSX (JavaScript XML) looks like HTML but lives inside JavaScript.
Explanation
- JSX makes UI code declarative & readable.
- Under the hood → compiled to plain JavaScript.
Important Rules
- Use
classNameinstead ofclass. - Event names → camelCase (
onClick,onChange). - Wrap multiple elements in
<div>or<>...</>.
Example
function Card() {
const title = "JSX Tips";
return (
<div className="card">
<h3>{title}</h3>
<p style={{ marginTop: 8 }}>Inline styles are objects.</p>
<>
<small>This is inside a fragment.</small>
</>
</div>
);
}
4. 📦 Props and State
🔹 Props
Definition → Inputs from parent → child (read-only).
Example
function UserBadge({ username, role = "Reader" }) {
return <span>@{username} — {role}</span>;
}
// Usage
<UserBadge username="tushar" role="Admin" />
<UserBadge username="guest" /> {/* defaults to Reader */}
🔹 State
Definition → Data that changes over time inside a component.
Managed with → useState hook.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h3>Count: {count}</h3>
<button onClick={() => setCount(count - 1)}>-</button>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
);
}
👉 Props = inputs | State = internal data.
5. 🖱 Event Handling
Definition
Event handling lets you capture user actions (clicks, typing, form submits).
Explanation
- Events use camelCase.
- You pass a function, not a string.
Example
import { useState } from "react";
function SignupForm() {
const [email, setEmail] = useState("");
function handleSubmit(e) {
e.preventDefault();
alert("Signed up: " + email);
setEmail("");
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@example.com"
/>
<button type="submit">Sign Up</button>
</form>
);
}
6. 🔀 Conditional Rendering
Definition
Conditionally show UI based on state/props.
Examples
// Using if
function Greeting({ isLoggedIn }) {
if (isLoggedIn) return <p>Welcome back!</p>;
return <p>Please sign in.</p>;
}
// Using &&
function Discount({ percent }) {
return <div>{percent >= 10 && <p>🎉 You have a discount!</p>}</div>;
}
// Using ternary
function Status({ online }) {
return <span>Status: {online ? "🟢 Online" : "⚪️ Offline"}</span>;
}
7. 📋 Lists and Keys
Definition
Render lists with .map(). Each element needs a unique key.
const products = [
{ id: "p1", name: "Keyboard" },
{ id: "p2", name: "Mouse" },
{ id: "p3", name: "Monitor" },
];
function ProductList() {
return (
<ul>
{products.map((p) => (
<li key={p.id}>{p.name}</li> // ✅ stable unique key
))}
</ul>
);
}
👉 Never use array indexes as keys (unless static).
8. 📝 Small Demo App – Todo App
Let’s combine everything: props, state, events, lists, conditional rendering.
import { useState } from "react";
function TodoItem({ todo, onToggle }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
<span style={{ textDecoration: todo.done ? "line-through" : "none" }}>
{todo.text}
</span>
</label>
</li>
);
}
function TodoApp() {
const [text, setText] = useState("");
const [todos, setTodos] = useState([
{ id: "t1", text: "Learn React", done: false },
{ id: "t2", text: "Build something", done: true },
]);
function addTodo(e) {
e.preventDefault();
if (!text.trim()) return;
setTodos((list) => [
{ id: crypto.randomUUID(), text, done: false },
...list,
]);
setText("");
}
function toggleTodo(id) {
setTodos((list) =>
list.map((t) => (t.id === id ? { ...t, done: !t.done } : t))
);
}
const remaining = todos.filter((t) => !t.done).length;
return (
<div>
<h2>Todos ({remaining} left)</h2>
<form onSubmit={addTodo}>
<input
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Add a todo..."
/>
<button type="submit">Add</button>
</form>
{todos.length === 0 ? (
<p>No todos yet. Add one!</p>
) : (
<ul>
{todos.map((t) => (
<TodoItem key={t.id} todo={t} onToggle={toggleTodo} />
))}
</ul>
)}
</div>
);
}
🔑 Recap
- React is a UI library that makes building apps easier and faster.
- Components → Reusable building blocks.
- JSX → Write HTML-like syntax in JS.
- Props → Pass data into components.
- State → Store dynamic data inside a component.
- Events → Handle user interactions.
- Conditional Rendering → Show UI based on conditions.
- Lists & Keys → Efficiently render multiple items.
Comments
Post a Comment