Tutorials React JS Components
Ch 5 / 46
Chapter 5 Beginner 9 min read React JS

React Components

Components are the fundamental building blocks of every React application. Just like LEGO bricks snap together to form any structure, React components compose to build entire UIs. In this chapter, you'll understand what a component really is, see how any real webpage can be broken down into a component tree, and learn the core principles of reusability and composition that make React so powerful.

Advertisement
What you'll learn
What a component is — the core definition and mental model
Anatomy of a component — structure, JSX return, and naming rules
UI → Component breakdown — how to see any webpage as a tree
Reusability & composition — write once, use anywhere
Component tree — parent, child and sibling relationships
Real-world use cases — e-commerce, dashboard, blog, SaaS
Rules & best practices — naming, single responsibility, and more
Your first component — working code examples you can run now

1. What Is a React Component?

A React component is a self-contained, reusable piece of UI. Think of it as a custom HTML element you define yourself — it can have its own structure (JSX), logic (JavaScript), and style — and you can use it anywhere in your app, as many times as you need.

At its most fundamental level, a React component is just a JavaScript function that returns JSX. That's it. No classes, no magic — just a function that describes what should appear on screen.

JavaScript Function
Every component is simply a JS function. It accepts inputs (props) and returns JSX — the description of what to render.
Foundation
Reusable
Write a <Button> once. Use it everywhere — in forms, modals, navbars, cards. One source of truth.
Key Feature
Composable
Components nest inside other components, like HTML elements do. A <Page> contains a <Navbar> which contains a <Logo>.
Composition
Self-Contained
Each component manages its own structure, behaviour and state. Changes inside one component don't accidentally break another.
Encapsulation
The LEGO Analogy Think of React components like LEGO bricks. Each brick (component) is a small, independent piece. You can combine simple bricks to make complex structures. The same brick can be used in many different models. React UIs work exactly the same way.

2. Anatomy of a Component

Let's dissect a component line by line so you can see exactly what each part does.

jsx — WelcomeCard.jsx — your first component
// ① Function definition — PascalCase name is REQUIRED
function WelcomeCard() {

  // ② JavaScript logic can go here (variables, calculations, etc.)
  const greeting = "Hello, React Developer!";

  // ③ Return JSX — describes what to render on screen
  return (
    <div className="card">
      <h2>{greeting}</h2>
      <p>Welcome to your first React component!</p>
    </div>
  );
}

// ④ Export so other files can use this component
export default WelcomeCard;
Component anatomy — 4 key parts
①
Function Name (PascalCase)
The function name must start with a capital letter — this tells React it's a component, not a regular HTML tag. WelcomeCard, UserProfile, ProductList are all valid. welcomeCard would be treated as an HTML element and fail silently.
②
JavaScript Logic
The function body is plain JavaScript. You can declare variables, call functions, compute values, and use hooks — anything you need before building your JSX output.
③
Return JSX
Every component must return JSX — the HTML-like syntax that describes what to display. Wrap multi-line JSX in parentheses ( ) to avoid automatic semicolon issues. A component must return a single root element (or use a <Fragment>).
④
Export
export default makes the component importable by other files. You can also use named exports: export function WelcomeCard() {} for multiple exports from one file.

Using (Rendering) a Component

Once defined, you use a component like a custom HTML tag — inside JSX of another component:

jsx — App.jsx — using WelcomeCard
import WelcomeCard from './WelcomeCard';

function App() {
  return (
    <div>
      {/* Use the component like an HTML tag */}
      <WelcomeCard />
      <WelcomeCard />  {/* You can use it multiple times! */}
      <WelcomeCard />
    </div>
  );
}

export default App;
Common Mistake — Lowercase Names Writing <welcomeCard /> (lowercase) tells React it's a standard HTML tag — React will try to find a DOM element called "welcomecard" and fail. Always use PascalCase for component names: <WelcomeCard />.
Advertisement

3. Seeing a Real Webpage as Components

The key skill in React is "thinking in components" — looking at any UI design and identifying the independent, reusable pieces. Below is a visual breakdown of how a typical e-commerce product listing page maps to a component tree.

Interactive Visual — E-commerce Page → Component Breakdown
🛍 Summer Sale — Up to 60% Off
Explore the latest collection of React-powered products
ProductList Component contains multiple ProductCard components:
React T-Shirt
₹499
JS Hoodie
₹899
Dev Mug
₹299
🔖 Categories
💰 Price Range
⭐ Rating
📦 Availability
Navbar Component HeroBanner Component ProductCard Component (×3) Sidebar Component Footer Component
How to Spot Component Boundaries Look for: (1) repeated UI elements — a card that appears 10 times is one ProductCard component used 10 times. (2) logically distinct sections — header, main, sidebar, footer. (3) independently updatable regions — if only the cart badge changes, it should be its own component.

The Code Behind That Diagram

jsx — ProductPage.jsx — composition in action
import { Navbar, HeroBanner, ProductCard, Sidebar, Footer } from './components';

const products = [
  { id: 1, name: "React T-Shirt", price: 499 },
  { id: 2, name: "JS Hoodie",    price: 899 },
  { id: 3, name: "Dev Mug",       price: 299 },
];

function ProductPage() {
  return (
    <div>
      <Navbar />

      <div className="layout">
        <main>
          <HeroBanner title="Summer Sale" />

          {/* Same ProductCard, different data each time */}
          {products.map(product => (
            <ProductCard
              key={product.id}
              name={product.name}
              price={product.price}
            />
          ))}
        </main>

        <Sidebar />
      </div>

      <Footer />
    </div>
  );
}

export default ProductPage;

4. The Component Tree

React organises your entire UI as a tree of components — exactly like the browser's DOM tree, but made of your custom components. Every React app has one root component (<App />) and every other component lives somewhere inside it.

Component Tree — E-commerce App
ReactDOM.createRoot
<App />
<Navbar />
Logo
NavLinks
CartIcon
<ProductPage />
HeroBanner
ProductCard ×3
Sidebar
<Footer />
FooterLinks
Socials
React entry point Root App component Page/section components Leaf/atomic components

In React, data flows downward through this tree (from parent to child via props). Every component only knows about its own children — not its siblings or grandparents. This predictable data flow is what makes React apps maintainable at scale.

5. Reusability — Write Once, Use Everywhere

The biggest power of components is reusability. Once you define a component, you can render it as many times as needed — with different data (props) each time. The logic, structure, and styling only need to be written once.

Team Page
Priya Sharma
Lead Developer
Author Box
Rahul Mehta
React Engineer
Review Card
Anita Patel
UX Designer

All three cards above are the same <UserCard /> component — just different props

jsx — UserCard.jsx — one component, many uses
// Define ONCE
function UserCard({ name, role, avatar }) {
  return (
    <div className="user-card">
      <img src={avatar} alt={name} />
      <h3>{name}</h3>
      <p>{role}</p>
    </div>
  );
}

// Use MANY TIMES — same component, different data
function TeamPage() {
  return (
    <section>
      <UserCard name="Priya Sharma"  role="Lead Developer" />
      <UserCard name="Rahul Mehta"  role="React Engineer" />
      <UserCard name="Anita Patel"  role="UX Designer"   />
    </section>
  );
}

6. Real-World Use Cases

Components appear in every kind of web application. Below are four common app types with their natural component breakdowns, so you can start "thinking in components" immediately.

App Type Page / Screen Components You'd Build Reused Across
🛒 E-Commerce Product Listing Navbar, SearchBar, ProductCard, Filters, Pagination, Footer ProductCard reused 50+ times
📊 Admin Dashboard Analytics Page Sidebar, StatCard, LineChart, DataTable, NotificationBell, Avatar StatCard, Avatar reused on every page
✍ Blog / CMS Article Page Header, ArticleCard, AuthorBio, TagBadge, CommentBox, TableOfContents TagBadge in listings & article pages
💼 SaaS App Settings Page SettingsPanel, FormInput, Toggle, Modal, Alert, Button, Breadcrumb Button, FormInput, Modal used app-wide
📱 Social Feed Home Feed TopNav, StoryBar, PostCard, LikeButton, CommentThread, UserSuggest LikeButton, Avatar, PostCard everywhere

Practical Example — ProductCard Component

Here's what a real-world ProductCard component looks like — notice how it takes all its data through props, keeping it 100% reusable:

jsx — ProductCard.jsx — a production-ready reusable component
function ProductCard({ name, price, image, rating, badge }) {
  return (
    <div className="product-card">

      {/* Optional badge — only renders if prop is passed */}
      {badge && <span className="badge">{badge}</span>}

      <img src={image} alt={name} className="product-img" />

      <div className="product-info">
        <h3>{name}</h3>
        <div className="rating">{"★".repeat(rating)}</div>
        <div className="price">₹{price}</div>
      </div>

      <button className="add-to-cart">Add to Cart</button>

    </div>
  );
}

// Usage — same component, different products
<ProductCard name="React T-Shirt" price={499} rating={5} badge="Sale" />
<ProductCard name="JS Hoodie"    price={899} rating={4} />
<ProductCard name="Dev Mug"       price={299} rating={4} badge="New" />
⚛ Build Real Projects at K2infocom
Learn React with hands-on projects, live training in Vadodara & online. Placement support included.
Explore React Courses

7. Component Rules & Best Practices

React enforces some strict rules about components, and the community has developed strong conventions. Knowing these from day one will save you hours of debugging.

Rule / Practice Why It Matters Status
PascalCase names — MyButton not myButton React uses casing to tell components apart from HTML tags Required
One component per file (recommended) Easier to find, test, and reuse components Convention
Never define a component inside another component Inner components re-create on every render, causing state bugs and performance issues Required
Single Responsibility Principle — one job per component Smaller components are easier to understand, test, and reuse Best Practice
Keep components pure — same input = same output Enables React to optimise re-renders and StrictMode to catch bugs Required
Return a single root element (or use <></>) JSX must have one parent. Fragments avoid extra DOM nodes. Required
jsx — ✅ correct vs ❌ incorrect patterns
// ❌ WRONG — component defined INSIDE another component
function Parent() {
  function Child() { // ← recreated every render!
    return <p>I'm the child</p>;
  }
  return <Child />;
}

// ✅ CORRECT — define at module level (outside)
function Child() {
  return <p>I'm the child</p>;
}

function Parent() {
  return <Child />;
}

// ❌ WRONG — multiple root elements
function Bad() {
  return (
    <h1>Title</h1>
    <p>Paragraph</p>  // ← Syntax error!
  );
}

// ✅ CORRECT — wrap in a fragment <></>
function Good() {
  return (
    <>
      <h1>Title</h1>
      <p>Paragraph</p>
    </>
  );
}

8. Quick Check

Knowledge Check — React Components
Q1. What is the minimum requirement for a React component to be valid?
✅ Answer
A React component must be a JavaScript function (or class) with a PascalCase name that returns JSX (or null). The function name must start with a capital letter — this is how React distinguishes components from regular HTML elements like <div>.
Q2. I have 20 product cards on a page. Should I write 20 separate components or 1 reusable one?
✅ Answer
Always one reusable component. Write a single ProductCard component that accepts props like name, price, and image. Then render it 20 times with different data: {products.map(p => <ProductCard key={p.id} {...p} />)}. This is the core value of component reusability.
Q3. Why should you never define a component inside another component?
✅ Answer
Every time the outer (parent) component re-renders, the inner component definition is recreated as a brand new function. React sees it as a completely different component type and will unmount and remount it — losing all its local state and causing unnecessary DOM mutations. Always define components at the module level (top of the file), never inside another function.
Q4. What is component composition and why does it matter?
✅ Answer
Composition means building complex UIs by combining small, focused components. Instead of one giant Page component with 500 lines, you compose: <Page> = <Navbar> + <Hero> + <ProductList> + <Footer>. This makes each piece independently testable, replaceable, and reusable across your app — the foundation of scalable React architecture.
Multiple Choice Questions
MCQ 1
Which of the following is a valid React component name?
MCQ 2
What does a React component function MUST return?
MCQ 3
You want to return two sibling elements from a component without adding an extra DOM node. What do you use?
MCQ 4
In React, data flows from __________ through the component tree.
Chapter 5 Summary
  • A React component is a JavaScript function with a PascalCase name that returns JSX — the UI description.
  • Components have 4 parts: function name → JS logic → JSX return → export.
  • Every webpage can be broken into a component tree — Navbar, Hero, Cards, Sidebar, Footer are all separate components.
  • Reusability means writing a component once (e.g., ProductCard) and using it many times with different props.
  • Composition means nesting components inside components to build complex UIs from simple pieces.
  • Data flows downward through the tree — from parent to child via props.
  • Never define a component inside another; always define at module level.
  • Return a single root element — use <></> Fragments to avoid extra DOM nodes.
Advertisement
Free Resource
React Components Cheatsheet
Anatomy, rules, composition patterns — one-page reference
Download PDF

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel