4. What Are Components in React, and How Do They Work
🧩 React Components
What are Components?
-
Components = building blocks of React apps.
-
Break complex UI into smaller, reusable pieces.
-
Makes development and maintenance of large apps easier.
Types of Components
-
Functional Components – Modern standard, examples below.
-
Class Components – Older style, less used now.
Think of components like JavaScript functions that return UI elements.
JSX (JavaScript + HTML)
-
Syntax for writing UI in React.
-
Looks like HTML but allows embedding JavaScript.
Example:
function Greeting() {
const name = "John";
return <h1 className="title">Hello {name}</h1>;
}
Notes on JSX
-
{}→ embed JavaScript inside JSX. -
classNameinstead ofclass(becauseclassis reserved in JS). -
Comments:
{/* Block Comments */}. -
Component names must start with a capital letter → React knows it’s a custom component.
-
Use components like
<Greeting />. -
All tags and components must be closed, even if empty:
<Greeting />.
Rendering Multiple Elements
-
Multiple sibling elements cannot exist alone in JSX.
-
Must wrap them in a parent element (like
div) or React Fragments.
function Greeting() {
const name = "John";
return (
<>
<h1>Hello {name}</h1>
<p>Nice to meet you.</p>
</>
);
}
-
<></>= shorthand for<Fragment></Fragment>. -
Allows multiple elements without adding extra HTML tags.
Key Takeaways
-
Components = reusable UI pieces.
-
JSX = HTML-like syntax with JS inside.
-
Always capitalize component names.
-
Use Fragments to wrap multiple elements.