DG
DevGuide
Run Code
Home/React/Components & JSX
⚛ React1 / 4

Components & JSX

📌 WHAT

A component is a reusable function that returns JSX — an HTML-like syntax embedded in JavaScript. React UIs are built entirely from composing components.

💡 WHY

Components enable reusability and encapsulation. Build a Button once, use it everywhere with different props. Each component manages its own appearance and logic.

⏰ WHEN / WHERE

Everything in React is a component: the whole page, the header, a button, a modal, a form input. If it appears on screen, it's a component.

🔧 HOW

Write a function with PascalCase name that returns JSX. Export it. Import and use it like an HTML tag.

📚Key Terms

JSX

— JavaScript XML — HTML-like syntax in JS files. Compiled to React.createElement() calls by Babel

PascalCase

— Naming convention for components: MyButton, UserCard. React distinguishes components from HTML tags by capitalization

Fragment (<>)

— Wrapper that lets you return multiple elements without adding extra DOM nodes

Children

— Content passed between component tags: <Card>This is children</Card>

Code Examples

#1Your first component

Your first component
tsx
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
// components/Button.tsx
interface ButtonProps {
label: string;
onClick: () => void;
variant?: "primary" | "secondary" | "danger";
disabled?: boolean;
}
// Component = function that returns JSX
function Button({ label, onClick, variant = "primary", disabled = false }: ButtonProps) {
const styles = {
primary: "bg-blue-500 hover:bg-blue-600 text-white",
secondary: "bg-gray-200 hover:bg-gray-300 text-gray-800",
danger: "bg-red-500 hover:bg-red-600 text-white",
};
return (
// className instead of class
// onClick handler in camelCase
<button
onClick={onClick}
disabled={disabled}
className={`px-4 py-2 rounded font-medium ${styles[variant]} ${
disabled ? "opacity-50 cursor-not-allowed" : ""
}`}
>
{label} {/* JavaScript expressions in {} */}
</button>
);
}
// JSX rules:
// ✅ Must return single root element (or Fragment <>)
// ✅ className instead of class
// ✅ htmlFor instead of for (on labels)
// ✅ All tags must be closed: <img /> <br />
// ✅ JavaScript in { curly braces }
// ✅ Component names MUST be PascalCase
// Usage in another component
function App() {
return (
<> {/* Fragment — no extra DOM node */}
<Button label="Save" onClick={() => console.log("saved")} />
<Button label="Delete" variant="danger" onClick={() => {}} />
<Button label="Loading..." disabled />
</>
);
}
export default Button;

Practice This Concept

Open the playground, paste any example, and experiment. The best way to learn is by breaking things.

Open in Playground