Popular Searches
Popular Course Categories
Popular Courses

Component Composition

Component Composition

React Components

Component Composition in React JS

Course Topic: Component Composition

Technology: React JS, JavaScript, JSX, HTML, CSS

Learning Objective: Understand how to combine multiple reusable React components to build organized, maintainable, and scalable user interfaces.


1. Introduction to Component Composition

Component Composition is a fundamental concept in React that involves combining small, independent components to create larger and more complex user interfaces. Instead of writing an entire application inside a single component, developers divide the UI into smaller components and compose them together.

Each component can handle a specific responsibility, such as displaying a navigation bar, rendering a product card, showing a profile, or presenting a footer. These components can then be combined inside a parent component to build a complete page.

For example, an e-commerce website may contain a Header, Navbar, ProductList, ProductCard, ShoppingCart, and Footer. By composing these components together, developers can create a complete shopping interface.

Example

function Header() {
  return <h1>My Website</h1>;
}
function Content() {
  return <p>Welcome to my website!</p>;
}
function Footer() {
  return <footer>Copyright 2026</footer>;
}
function App() {
  return (
    <div>
      <Header />
      <Content />
      <Footer />
    </div>
  );
}
export default App;

In this example, the App component combines Header, Content, and Footer to create a complete page. This is a basic example of Component Composition.


2. Why Is Component Composition Important?

Component Composition helps developers organize applications into manageable parts. It reduces unnecessary duplication and makes components easier to understand, test, reuse, and maintain.

  • Reusability: The same component can be used in multiple places.
  • Maintainability: A change to one component can be made without rewriting the entire application.
  • Readability: Smaller components make code easier to understand.
  • Separation of concerns: Each component can focus on a particular UI responsibility.
  • Scalability: New features can be added by composing existing components and introducing new ones.
  • Consistency: Reusing the same component helps maintain a consistent design across pages.
  • Testing: Individual components can be tested separately.

3. Understanding Parent and Child Components

In React, a component can render other components inside its JSX. The component that renders another component is commonly called the parent, while the rendered component is called the child.

Example

function WelcomeMessage() {
  return <h2>Welcome to React!</h2>;
}
function HomePage() {
  return (
    <main>
      <h1>Home Page</h1>
      <WelcomeMessage />
    </main>
  );
}
export default HomePage;

Here, HomePage is the parent component, and WelcomeMessage is its child. The parent composes its own heading and the child component into one interface.

Important Points

  • React component names should begin with an uppercase letter.
  • A custom component is rendered using JSX syntax, such as <WelcomeMessage />.
  • A component can contain multiple child components.
  • Parent components can pass information to children using props.
  • Components can also receive JSX content through the special children prop.

4. Component Composition Using Props

Props allow a parent component to pass data to a child component. This makes it possible to reuse one component with different values instead of creating a separate component for every item.

Example: Reusable User Profile

function UserProfile({ name, role }) {
  return (
    <section>
      <h2>{name}</h2>
      <p>Role: {role}</p>
    </section>
  );
}
function App() {
  return (
    <div>
      <UserProfile name="Amit" role="Developer" />
      <UserProfile name="Priya" role="Designer" />
      <UserProfile name="Rahul" role="Tester" />
    </div>
  );
}
export default App;

In this example, UserProfile is reused three times. Each instance receives different props, allowing it to display different user information.

Advantages of Props-Based Composition

  • Reduces repeated JSX and duplicated code.
  • Makes components flexible and configurable.
  • Separates data from presentation.
  • Supports reusable components throughout the application.

5. Component Composition Using the children Prop

The children prop is one of the most useful techniques for component composition. When content is placed between a component's opening and closing tags, React passes that content to the component through the children prop.

This technique is especially useful for reusable containers, cards, panels, dialogs, layouts, and other wrapper components.

Example: Reusable Card Component

function Card({ children }) {
  return (
    <div className="card">
      {children}
    </div>
  );
}
function App() {
  return (
    <div>
      <Card>
        <h2>React JS</h2>
        <p>Learn component composition.</p>
      </Card>
      <Card>
        <h2>JavaScript</h2>
        <p>Learn modern JavaScript concepts.</p>
      </Card>
    </div>
  );
}
export default App;

Here, Card does not need to know which content it will display. It simply wraps whatever JSX the parent passes into it.

CSS Example

.card {
  padding: 20px;
  margin: 12px 0;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: #f9f9f9;
}

Key Benefits

  • Allows the same wrapper to display different content.
  • Improves flexibility and reusability.
  • Reduces the need for components to know about the details of their inner content.
  • Makes it easier to create consistent UI layouts.

6. Composition Through Multiple Components

A React component can combine several smaller components. This approach is useful when a page contains multiple independent UI sections.

Example: Website Layout

function Header() {
  return <header><h1>My Store</h1></header>;
}
function Navigation() {
  return (
    <nav>
      <a href="/">Home</a>
      {" | "}
      <a href="/products">Products</a>
      {" | "}
      <a href="/contact">Contact</a>
    </nav>
  );
}
function MainContent() {
  return (
    <main>
      <h2>Featured Products</h2>
      <p>Explore our latest collection.</p>
    </main>
  );
}
function Footer() {
  return <footer>My Store - All rights reserved.</footer>;
}
function App() {
  return (
    <div>
      <Header />
      <Navigation />
      <MainContent />
      <Footer />
    </div>
  );
}
export default App;

Each component manages one part of the website, while App brings all parts together. This structure makes the page easier to maintain as the project grows.


7. Building a Product List Using Component Composition

Product lists are a common example of composition in real-world React applications. A ProductCard component displays one product, while ProductList combines multiple ProductCard components into a list.

ProductCard.jsx

function ProductCard({ product }) {
  return (
    <article className="product-card">
      <h3>{product.name}</h3>
      <p>Price: ₹{product.price}</p>
    </article>
  );
}
export default ProductCard;

ProductList.jsx

import ProductCard from "./ProductCard";
function ProductList() {
  const products = [
    { id: 1, name: "Laptop", price: 55000 },
    { id: 2, name: "Headphones", price: 2500 },
    { id: 3, name: "Keyboard", price: 1500 }
  ];
  return (
    <section>
      <h2>Available Products</h2>
      <div className="product-list">
        {products.map((product) => (
          <ProductCard key={product.id} product={product} />
        ))}
      </div>
    </section>
  );
}
export default ProductList;

App.jsx

import ProductList from "./ProductList";
function App() {
  return (
    <main>
      <h1>Online Store</h1>
      <ProductList />
    </main>
  );
}
export default App;

In this example, App renders ProductList, and ProductList renders multiple ProductCard instances. The key prop gives React a stable identifier for each item in the rendered list.


8. Composition Versus Inheritance

Inheritance is a programming technique in which one class derives behavior from another class. In React, composition is generally the preferred approach for combining UI elements and sharing flexible presentation patterns.

Component Composition Inheritance
Combines components to create a UI. Derives functionality from a parent class.
Uses nested JSX, props, and children. Uses class-based inheritance.
Encourages flexible and reusable UI structures. Can create tighter dependencies between classes.
Commonly used to structure React interfaces. Not the usual approach for sharing UI behavior in React.
Components can be combined in different ways. Behavior is organized around class relationships.

Conclusion: For most React UI reuse needs, prefer composition with props and children rather than designing components around inheritance hierarchies.


9. Component Composition and Reusability

Reusable components can be composed in different places while maintaining a consistent appearance and behavior. A button component, for example, can be reused on forms, product cards, and navigation sections.

Example: Reusable Button

function Button({ children, onClick, variant = "primary" }) {
  return (
    <button
      className={`button button-${variant}`}
      onClick={onClick}
    >
      {children}
    </button>
  );
}
function App() {
  return (
    <div>
      <Button onClick={() => alert("Saved!")}>
        Save
      </Button>
      <Button
        variant="secondary"
        onClick={() => alert("Cancelled!")}
      >
        Cancel
      </Button>
    </div>
  );
}
export default App;

The Button component receives its label through children, its action through onClick, and its visual style through variant. This allows the same component to support multiple use cases.


10. Passing JSX Through Named Props

Besides the special children prop, a component can receive JSX through ordinary named props. This is helpful when a component needs several different content areas, such as a header, body, and footer.

Example

function Panel({ title, content, actions }) {
  return (
    <section className="panel">
      <header>{title}</header>
      <div>{content}</div>
      <footer>{actions}</footer>
    </section>
  );
}
function App() {
  return (
    <Panel
      title={<h2>Account Settings</h2>}
      content={<p>Update your profile information.</p>}
      actions={<button>Save Changes</button>}
    />
  );
}
export default App;

Named JSX props allow a component to accept multiple distinct content slots. This is often useful for layouts, dialogs, dashboards, and configurable panels.


11. Component Composition With Conditional Rendering

Composition can be combined with conditional rendering to show different components depending on application state or props.

Example

function LoginMessage() {
  return <p>Please log in to continue.</p>;
}
function Dashboard() {
  return <h2>Welcome to your dashboard!</h2>;
}
function App() {
  const isLoggedIn = true;
  return (
    <main>
      {isLoggedIn ? <Dashboard /> : <LoginMessage />}
    </main>
  );
}
export default App;

The App component composes one of two child components depending on the value of isLoggedIn. In a real application, this value might come from authentication state or another data source.


12. Component Composition and Separation of Concerns

Separation of concerns means dividing an application into parts with clearly defined responsibilities. With component composition, a parent component can organize the overall layout while child components handle specific presentation or behavior.

Component Responsibility
Header Displays the website title or brand.
Navigation Displays navigation links.
ProductList Organizes a collection of products.
ProductCard Displays information about one product.
Footer Displays copyright and supporting information.
App Composes the main application interface.

This structure prevents a single component from becoming too large and makes individual sections easier to understand and update.


13. Best Practices for Component Composition

  • Keep components focused: Give each component a clear and understandable responsibility.
  • Reuse components when appropriate: Avoid copying the same UI markup across multiple pages.
  • Use props for configuration: Pass data and callbacks instead of hardcoding different values in the same component.
  • Use children for flexible wrappers: Prefer children when a component needs to wrap arbitrary JSX content.
  • Choose meaningful names: Names such as ProductCard, UserProfile, and PageHeader explain a component's purpose.
  • Keep props readable: Avoid passing large numbers of unrelated props to one component.
  • Use stable keys in lists: When rendering arrays of components, provide a unique and stable key for each item.
  • Avoid excessive nesting: Break complex layouts into smaller components when doing so improves clarity.
  • Keep data flow clear: Pass information through props or appropriate shared state mechanisms.
  • Prefer composition over inheritance: Build interfaces by combining components rather than creating complex inheritance structures.
  • Avoid unnecessary abstractions: Not every small JSX expression needs to become a separate component.

14. Common Mistakes in Component Composition

Mistake Why It Is a Problem Better Approach
Using lowercase names for custom components JSX treats lowercase tags as built-in or HTML elements. Use uppercase names, such as ProductCard.
Repeating the same UI markup Increases duplication and maintenance work. Extract a reusable component.
Forgetting to render children Nested content passed to a wrapper will not appear unless rendered. Include {children} in the returned JSX.
Passing the wrong prop name The child may receive undefined instead of the expected value. Check prop names in both parent and child.
Missing keys in mapped lists React may display a warning and have difficulty matching list items. Use a stable unique key, such as an item ID.
Creating an unnecessarily large component Makes code harder to understand and test. Split meaningful UI responsibilities into components.
Overusing generic wrapper components Can make the component hierarchy unnecessarily complex. Create abstractions when they provide clear reuse or readability benefits.

15. Practical Project: Compose a Student Dashboard

Project Objective: Create a simple student dashboard by composing reusable React components.

Requirements

  • Create a DashboardHeader component.
  • Create a StudentProfile component that accepts name and course props.
  • Create a CourseCard component that displays a course title and progress.
  • Create a CourseList component that renders multiple CourseCard components.
  • Combine the components inside a Dashboard component.

Example Implementation

function DashboardHeader() {
  return <header><h1>Student Dashboard</h1></header>;
}
function StudentProfile({ name, course }) {
  return (
    <section>
      <h2>Welcome, {name}!</h2>
      <p>Enrolled Course: {course}</p>
    </section>
  );
}
function CourseCard({ title, progress }) {
  return (
    <article>
      <h3>{title}</h3>
      <p>Progress: {progress}%</p>
    </article>
  );
}
function CourseList() {
  const courses = [
    { id: 1, title: "React JS", progress: 70 },
    { id: 2, title: "JavaScript", progress: 90 },
    { id: 3, title: "HTML and CSS", progress: 100 }
  ];
  return (
    <section>
      <h2>My Courses</h2>
      {courses.map((course) => (
        <CourseCard
          key={course.id}
          title={course.title}
          progress={course.progress}
        />
      ))}
    </section>
  );
}
function Dashboard() {
  return (
    <div>
      <DashboardHeader />
      <StudentProfile name="Aarav" course="Frontend Development" />
      <CourseList />
    </div>
  );
}
export default Dashboard;

Expected Result

The page displays a dashboard heading, a personalized student welcome message, and a list of courses with progress values. The components are independent and reusable, and the Dashboard component composes them into a complete interface.

Possible Enhancements

  • Add CSS styling to the dashboard.
  • Display course progress using progress bars.
  • Add a reusable Button component for course actions.
  • Pass student and course data from an API.
  • Add conditional rendering for completed courses.

16. Component Composition Interview Questions and Answers

Q1. What is Component Composition in React?

Answer: Component Composition is the process of combining smaller React components to build larger user interfaces.

Q2. Why is Component Composition useful?

Answer: It improves reusability, readability, maintainability, and separation of concerns.

Q3. What is a parent component?

Answer: A parent component is a component that renders one or more other components inside its JSX.

Q4. What is a child component?

Answer: A child component is a component rendered by another component.

Q5. What are props in React?

Answer: Props are read-only inputs passed from a parent component to a child component.

Q6. What is the children prop?

Answer: The children prop contains the content nested between a component's opening and closing JSX tags.

Q7. How does composition differ from inheritance?

Answer: Composition combines components to build an interface, while inheritance derives functionality through class relationships. React generally favors composition for UI reuse.

Q8. Can a component render multiple child components?

Answer: Yes. A component can render several child components and combine them inside a Fragment or a suitable HTML element.

Q9. Can a component accept JSX through a prop other than children?

Answer: Yes. JSX can be passed through named props such as header, content, or actions.

Q10. What is a reusable component?

Answer: A reusable component is a component designed to be used in multiple places, often with different props or children.

Q11. Why are keys used when rendering lists of components?

Answer: Keys help React identify list items between renders so it can match items correctly when the list changes.

Q12. Should every part of a page become a separate component?

Answer: No. Components should be extracted when doing so improves clarity, reuse, testing, or maintenance. Excessive abstraction can make code harder to follow.


17. Practice Exercises

  1. Create a Header component and render it inside an App component.
  2. Create a reusable ProfileCard component that accepts name and profession props.
  3. Create a Card component that displays arbitrary nested JSX using children.
  4. Create a ProductCard component and reuse it to display at least four products.
  5. Create a PageLayout component that combines Header, MainContent, and Footer.
  6. Create a Panel component with separate title, content, and actions props.
  7. Build a Student Dashboard using at least five reusable components.
  8. Render a list of course components from an array and provide stable keys.

18. Quick Revision Checklist

  • Understand the meaning and purpose of Component Composition.
  • Know how parent and child components work together.
  • Understand how props pass data between components.
  • Know how to use the children prop for nested JSX.
  • Be able to compose a page using multiple components.
  • Understand how to render lists of reusable components.
  • Know why stable keys are important in lists.
  • Understand why React generally favors composition over inheritance for UI reuse.
  • Recognize common composition mistakes and how to avoid them.
  • Practice building a small application from reusable components.

19. Official React Documentation


20. React JS Training and Course Demo

Learn more about React JS training, component-based development, JSX, props, reusable UI design, and other frontend development concepts through the following links.


Conclusion

Component Composition is a core React concept that allows developers to build complete interfaces by combining smaller, reusable components. Props make components configurable, while the children prop makes wrapper components flexible. By applying these techniques, developers can create React applications that are easier to understand, test, maintain, and extend.

Previous Next
whatsapp