Components & JSX
A component is a reusable function that returns JSX — an HTML-like syntax embedded in JavaScript. React UIs are built entirely from composing components.
Components enable reusability and encapsulation. Build a Button once, use it everywhere with different props. Each component manages its own appearance and logic.
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.
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
// components/Button.tsxinterface ButtonProps {label: string;onClick: () => void;variant?: "primary" | "secondary" | "danger";disabled?: boolean;}// Component = function that returns JSXfunction 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<buttononClick={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 componentfunction 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