Skip to Content
FrontendReactBasics1.3 React Components

Components 🧱

Components are the smallest reusable building blocks in React. Think LEGO bricks: snap them together to form larger structures.

1) Functional Components ⚛️

  • A component is a plain function returning JSX.
  • Names are PascalCase; return a single root element.
function Badge({ label }) { return <span className="badge">{label}</span>; }

🧠 Treat components as pure functions of props wherever possible.

2) Props and Defaults 🧠

Props are the inputs to a component. They are read-only and flow top → down.

function Alert({ tone = "info", children }) { const toneClasses = { info: "bg-blue", success: "bg-green", danger: "bg-red" }; return ( <section className={toneClasses[tone]}> {children} </section> ); }
  • Provide sensible defaults to keep call sites clean.
  • Destructure props for clarity.

3) Children and Composition 🧩

children lets parents inject arbitrary JSX into a component.

function Card({ title, children }) { return ( <article className="card"> <h2>{title}</h2> <div>{children}</div> </article> ); } <Card title="Profile"> <Avatar /> <ProfileDetails /> </Card>
  • Compose UI like nested boxes.
  • Pass render props (functions) for advanced patterns when needed.

4) Conditional Rendering ✅❌

  • Use early returns for simple branches.
  • Use && for short-circuit conditions; ternaries for two outcomes.
function Dashboard({ isLoading, stats }) { if (isLoading) return <p>Loading...</p>; if (!stats?.length) return <p>No stats yet.</p>; return <StatsList items={stats} />; }

5) Rendering Lists + Keys 🔄

key helps React reconcile list items correctly.

function TodoList({ todos }) { return ( <ul> {todos.map(todo => ( <li key={todo.id}> {todo.done ? "✅" : "⬜"} {todo.label} </li> ))} </ul> ); }
  • Prefer stable IDs over array indexes.
  • Keys live on the element returned by .map().

Key Takeaways ✅

  • Components are pure functions; props are read-only inputs.
  • children powers composition, letting components wrap others.
  • Conditional UI stays readable with early returns and ternaries.
  • Provide stable key values so reconciliation keeps state aligned.

Recap 🔄

Functional components receive props, optionally render children, and compose into trees. Keep logic simple, branch early for conditional UI, and remember that lists need keys so React can reconcile efficiently.

Last updated on