Topic 3 of 15 · React Developer

Topic 3 : React Components

Lesson TL;DRTopic 3: React Components 📖 6 min read · 🎯 beginner · 🧭 Prerequisites: introductiontoreact, reactstructure ⚠️ Note: this lesson was regenerated because the source content did not match the title. W...
6 min read·beginner·react · components · jsx · props

Topic 3: React Components

📖 6 min read · 🎯 beginner · 🧭 Prerequisites: introduction-to-react, react-structure

⚠️ Note: this lesson was regenerated because the source content did not match the title.

Why this matters

Here's the thing — when you first open a React project, the word "component" gets thrown around everywhere, and it can feel like everyone else just gets it while you're still guessing. Let me clear that up right now. A component is simply a reusable piece of your UI — think of it like a building block, a LEGO brick. Every button, every card, every navbar you see on a React app is a component. Once you understand what a component is, how to write one, and how components share information through something called props, you'll start seeing React the way it was meant to be seen.

What You'll Learn

  • What a React component is and why it is the core building block of every React app
  • How to write functional components using modern React syntax
  • How JSX is transformed into real UI output
  • How to pass data between components using props
  • How to compose small components into larger interfaces

The Analogy

Think of a React component like a custom LEGO brick you design yourself. Each brick has a fixed shape (its structure), a fixed color scheme (its styles), and a set of pins on top where other bricks snap in (its props). Once you design that brick, you can stamp out as many copies as you want — each copy identical in shape but potentially holding different data through its pins. A Button brick looks the same everywhere, but one says "Submit" and another says "Cancel" because different data was plugged into its pins. The whole page is just bricks snapped together, and React is the instruction manual that keeps every brick in sync.

Chapter 1: What Is a React Component?

A component is a self-contained, reusable piece of UI. It is a JavaScript function (or class) that:

  1. Accepts input data called props
  2. Returns JSX describing what should appear on screen

React applications are built by composing many components together — small ones nested inside larger ones — forming a tree rooted at a single top-level component (usually <App />).

There are two styles of component in React:

StyleSyntaxWhen to use
Functional componentPlain JavaScript functionDefault choice — modern React
Class componentES6 class extending React.ComponentLegacy codebases only

Modern React uses functional components for everything. Class components still appear in older projects, so you should be able to read them.

Chapter 2: Writing a Functional Component

A functional component is just a function whose name starts with a capital letter and returns JSX.

function Greeting() {
  return <h1>Hello, Vizag!</h1>;
}

That's it. Greeting is a fully valid React component. You render it in JSX like an HTML tag:

function App() {
  return (
    <div>
      <Greeting />
    </div>
  );
}

Rules React enforces on component names

  • Must start with a capital letter. <greeting /> is treated as a plain HTML element. <Greeting /> triggers the component.
  • Must return a single root element. Wrap sibling elements in a <div> or a React Fragment (<>…</>).
// ❌ Two root elements — React will error
function Bad() {
  return (
    <h1>Title</h1>
    <p>Paragraph</p>
  );
}

// ✅ Wrapped in a Fragment — no extra DOM node
function Good() {
  return (
    <>
      <h1>Title</h1>
      <p>Paragraph</p>
    </>
  );
}

Chapter 3: JSX — The Language of Components

JSX is a syntax extension that lets you write HTML-like markup inside JavaScript. It looks like HTML but it is not — under the hood, the build tool (Babel or the React compiler) transforms each JSX element into a React.createElement(...) call.

// What you write
const element = <h1 className="title">Hello</h1>;

// What the compiler produces
const element = React.createElement("h1", { className: "title" }, "Hello");

Key JSX rules to memorise

  1. classclassNameclass is a reserved word in JavaScript.
  2. forhtmlFor — same reason, used on <label> elements.
  3. Self-close empty tags. <img> must be <img />, <input> must be <input />.
  4. Expressions go in curly braces. To embed JavaScript inside JSX, wrap it in {}.
const name = "Vizag";
const element = <p>Welcome to {name}!</p>;
// Renders: <p>Welcome to Vizag!</p>

You can use any valid JavaScript expression inside {}: variables, function calls, ternary operators, arithmetic — but not if statements or for loops (use .map() and ternaries instead).

function StatusBadge({ isOnline }) {
  return (
    <span className={isOnline ? "badge--green" : "badge--red"}>
      {isOnline ? "Online" : "Offline"}
    </span>
  );
}

Chapter 4: Props — Passing Data into Components

Props (short for properties) are the mechanism React uses to pass data from a parent component down to a child component. Props flow in one direction only: parent → child.

A functional component receives props as its first argument — an object where each key is one prop name.

function WelcomeBanner(props) {
  return <h2>Welcome, {props.username}!</h2>;
}

The parent passes data as attributes on the JSX tag:

function App() {
  return <WelcomeBanner username="Anaya" />;
}
// Renders: <h2>Welcome, Anaya!</h2>

Destructuring props (preferred pattern)

Destructuring makes the code cleaner and shows the component's API at a glance:

function WelcomeBanner({ username, role }) {
  return (
    <div>
      <h2>Welcome, {username}!</h2>
      <p>Role: {role}</p>
    </div>
  );
}

// Usage
<WelcomeBanner username="Anaya" role="Architect" />

Default prop values

You can provide fallback values directly in the destructuring:

function WelcomeBanner({ username = "Guest", role = "Visitor" }) {
  return (
    <div>
      <h2>Welcome, {username}!</h2>
      <p>Role: {role}</p>
    </div>
  );
}

Props are read-only

A component must never modify its own props. Props are owned by the parent. If a child needs to communicate back up, the parent passes a callback function as a prop — the child calls it.

function LikeButton({ onLike }) {
  return <button onClick={onLike}>👍 Like</button>;
}

function Post() {
  function handleLike() {
    console.log("Post liked!");
  }
  return <LikeButton onLike={handleLike} />;
}

Chapter 5: The children Prop

React reserves one special prop name: children. It holds whatever JSX is placed between a component's opening and closing tags.

function Card({ children }) {
  return <div className="card">{children}</div>;
}

// Usage — anything between <Card>...</Card> becomes children
function App() {
  return (
    <Card>
      <h3>Vizag News</h3>
      <p>The class meets at dawn.</p>
    </Card>
  );
}

This makes components flexible containers without needing to know in advance what content they'll wrap.

Chapter 6: Component Composition

Building a React UI means composing small, focused components into larger ones. Each component should do one thing well.

function Avatar({ src, alt }) {
  return <img src={src} alt={alt} className="avatar" />;
}

function UserInfo({ name, title, avatarSrc }) {
  return (
    <div className="user-info">
      <Avatar src={avatarSrc} alt={name} />
      <div>
        <strong>{name}</strong>
        <p>{title}</p>
      </div>
    </div>
  );
}

function CouncilCard({ member }) {
  return (
    <div className="council-card">
      <UserInfo
        name={member.name}
        title={member.title}
        avatarSrc={member.avatarSrc}
      />
    </div>
  );
}

Notice how CouncilCard doesn't know how Avatar or UserInfo work internally — it just composes them. This layering is the core design principle behind every React codebase.

graph TD
  App --> CouncilCard
  CouncilCard --> UserInfo
  UserInfo --> Avatar
  UserInfo --> NameBlock["Name + Title div"]

Chapter 7: Class Components (Reading Legacy Code)

You will encounter class components in older codebases. The equivalent of the WelcomeBanner function above looks like this as a class:

import React, { Component } from "react";

class WelcomeBanner extends Component {
  render() {
    const { username, role } = this.props;
    return (
      <div>
        <h2>Welcome, {username}!</h2>
        <p>Role: {role}</p>
      </div>
    );
  }
}

Key differences from functional components:

  • Extends React.Component
  • Must implement a render() method that returns JSX
  • Props are accessed via this.props (not a function argument)
  • State is accessed via this.state and mutated via this.setState()

Modern code does not need class components — hooks (covered later) give functional components all the same capabilities.

🧪 Try It Yourself

Task: Build a ProfileCard component that accepts three props — name (string), role (string), and isActive (boolean) — and renders a card. When isActive is true, display a green "Active" badge; when false, display a grey "Inactive" badge.

Success criterion: Rendering <ProfileCard name="the trainer" role="Language Grammarian" isActive={true} /> should show the name, role, and a green "Active" badge in the browser.

Starter snippet:

function ProfileCard({ name, role, isActive }) {
  return (
    <div style={{ border: "1px solid #ccc", padding: "16px", borderRadius: "8px" }}>
      <h3>{name}</h3>
      <p>{role}</p>
      {/* Replace this comment with the badge */}
    </div>
  );
}

export default ProfileCard;

Render it in App.jsx:

import ProfileCard from "./ProfileCard";

function App() {
  return (
    <div>
      <ProfileCard name="the trainer" role="Language Grammarian" isActive={true} />
      <ProfileCard name="the trainer" role="City Governor" isActive={false} />
    </div>
  );
}

export default App;

🔍 Checkpoint Quiz

Q1. Why must a React component name start with a capital letter?

A) JavaScript requires all functions to be capitalised
B) React uses the capitalisation to distinguish custom components from native HTML tags
C) Babel cannot process lowercase component names
D) It is only a style convention with no functional impact

Q2. Given this snippet, what does it render?

function Tag({ label, color = "blue" }) {
  return <span style={{ color }}>{label}</span>;
}

// Rendered as:
<Tag label="React" />

A) A span with no text and no color
B) A span with the text "React" in blue
C) An error, because color prop is missing
D) A span with the text "React" in the browser's default color

Q3. What is wrong with this component?

function BadComponent(props) {
  props.count = props.count + 1;
  return <p>{props.count}</p>;
}

A) props.count is not a valid prop name
B) The function must use destructuring instead of props
C) Components must not mutate their props — props are read-only
D) Adding 1 to a prop is a type error in JSX

Q4. You have a Modal component that needs to render different content each time it is used. Which React feature allows the parent to pass arbitrary JSX into the modal without the modal knowing what that content will be in advance?

A) defaultProps
B) The children prop
C) A content state variable
D) React.cloneElement

A1. B — React checks capitalisation at the JSX transform stage. Lowercase tags are treated as native HTML elements; capitalised tags trigger a component lookup.

A2. B — color defaults to "blue" when the prop is not supplied, and label="React" provides the text.

A3. C — Props are immutable from the component's perspective. Mutating props directly violates React's data-flow model and can cause unpredictable bugs. Use local state or a parent-provided callback instead.

A4. B — The children prop holds any JSX placed between a component's opening and closing tags, making the component a flexible container for arbitrary content.

🪞 Recap

  • A React component is a JavaScript function that accepts props and returns JSX describing a piece of UI.
  • Component names must start with a capital letter so React can distinguish them from native HTML elements.
  • JSX uses className instead of class, self-closes empty tags, and embeds JavaScript expressions inside {}.
  • Props flow one way — parent to child — and are always read-only inside the receiving component.
  • The special children prop holds any JSX nested between a component's opening and closing tags.
  • Composing small, focused components into larger ones is the central design pattern of every React application.

📚 Further Reading

Like this topic? It’s one of 15 in React Developer.

Block your seat for ₹2,500 and join the next cohort.