Popular Searches
Popular Course Categories
Popular Courses

Nested Components

Nested Components

React Components

Nested Components in React JS

Nested Components are an important concept in React JS that allows developers to build complex user interfaces by placing one component inside another component. Instead of creating an entire website in a single component, developers can divide the interface into smaller, reusable components and combine them to create a complete application.

For example, a website page may contain a Header component, Navbar component, Sidebar component, MainContent component, and Footer component. These components can be rendered inside a parent component to form the complete page layout.

Course: React JS Training

Course Link: JustAcademy React JS Training Course

Demo Link: Register for React JS Course Demo


1. What Are Nested Components?

Nested Components refer to the practice of rendering one React component inside another component. The component that renders another component is commonly called the parent component, while the component being rendered is called the child component.

Nested components help organize application structure, reuse UI elements, and separate different parts of a website into manageable sections.

Example:

function Header() {
  return <h1>Welcome to My Website</h1>;
}
function App() {
  return (
    <div>
      <Header />
      <p>This is the home page.</p>
    </div>
  );
}
export default App;

Explanation:

  • Header is a child component.
  • App is the parent component.
  • <Header /> renders the Header component inside App.
  • The browser displays the heading and the paragraph as part of the same interface.

2. Understanding Parent and Child Components

In React, components can be arranged in a hierarchy. A parent component can render one or more child components, and those children can render additional components.

Example:

function Logo() {
  return <h1>My Website</h1>;
}
function Navbar() {
  return <nav>Home | About | Contact</nav>;
}
function Header() {
  return (
    <header>
      <Logo />
      <Navbar />
    </header>
  );
}
function App() {
  return (
    <div>
      <Header />
    </div>
  );
}
export default App;

Component hierarchy:

App
 └── Header
      ├── Logo
      └── Navbar

Here, App renders Header, while Header renders Logo and Navbar. This creates a clear component hierarchy.

3. Why Are Nested Components Used?

  • Code organization: Divides a large interface into smaller logical sections.
  • Reusability: Allows developers to reuse existing components in different places.
  • Maintainability: Makes individual UI sections easier to update and debug.
  • Readability: Helps developers understand the structure of an application.
  • Consistency: Keeps repeated UI elements consistent across pages.
  • Scalability: Makes it easier to add new features to growing applications.
  • Separation of responsibilities: Each component can focus on a specific part of the interface.

4. Basic Syntax of Nested Components

A component can be nested inside another component by using its name as a JSX tag. Custom component names must start with a capital letter.

function ChildComponent() {
  return <p>This is the child component.</p>;
}
function ParentComponent() {
  return (
    <div>
      <h2>Parent Component</h2>
      <ChildComponent />
    </div>
  );
}
export default ParentComponent;

In this example, ParentComponent renders ChildComponent inside its JSX. Both component functions are defined separately at the top level of the module.

5. Creating Nested Components Step by Step

Step 1: Create the Child Component

Create a component that displays a simple message.

function Message() {
  return <p>Welcome to React JS!</p>;
}

Step 2: Create the Parent Component

Create another component that includes the Message component.

function App() {
  return (
    <div>
      <h1>My React Application</h1>
      <Message />
    </div>
  );
}
export default App;

Step 3: Render the Parent Component

In a standard React project, the entry file imports App and renders it into the root DOM element.

import { createRoot } from "react-dom/client";
import App from "./App";

createRoot(document.getElementById("root")).render(<App />);

Ensure that the HTML page contains an element with the ID root and that the project entry file is configured correctly.

Step 4: View the Output

The browser displays the heading “My React Application” followed by the message “Welcome to React JS!”.

6. Nesting Multiple Components

A parent component can render several child components to build a complete interface.

function Header() {
  return <h1>Online Learning Platform</h1>;
}
function Sidebar() {
  return <aside>Course Categories</aside>;
}
function MainContent() {
  return <main>Explore Our Courses</main>;
}
function Footer() {
  return <footer>Contact Us</footer>;
}
function App() {
  return (
    <div>
      <Header />
      <Sidebar />
      <MainContent />
      <Footer />
    </div>
  );
}
export default App;

The App component combines four child components into one page. Each component is responsible for a specific section of the interface.

7. Deeply Nested Components

Deep nesting occurs when a component renders another component, which then renders additional components. This creates multiple levels in the component hierarchy.

function Button() {
  return <button>Learn More</button>;
}
function CourseCard() {
  return (
    <article>
      <h3>React JS Training</h3>
      <p>Learn to build modern user interfaces.</p>
      <Button />
    </article>
  );
}
function CourseSection() {
  return (
    <section>
      <h2>Our Courses</h2>
      <CourseCard />
    </section>
  );
}
function App() {
  return (
    <div>
      <CourseSection />
    </div>
  );
}
export default App;

Component hierarchy:

App
 └── CourseSection
      └── CourseCard
           └── Button

This structure allows each component to focus on a particular part of the course interface.

8. Passing Props to Nested Components

Props allow parent components to pass data to child components. This makes nested components flexible and reusable.

function StudentInfo({ name, course }) {
  return (
    <div>
      <h3>{name}</h3>
      <p>Course: {course}</p>
    </div>
  );
}
function StudentSection() {
  return (
    <section>
      <h2>Student Details</h2>
      <StudentInfo name="Amit" course="React JS" />
      <StudentInfo name="Priya" course="JavaScript" />
    </section>
  );
}
function App() {
  return <StudentSection />;
}
export default App;

Explanation:

  • StudentSection is the parent of the StudentInfo instances.
  • name and course are passed as props.
  • The same child component displays different student information.
  • Props should be treated as read-only inputs.

9. Using the Children Prop in Nested Components

The special children prop allows a component to receive and display content placed between its opening and closing JSX tags.

function Card({ children }) {
  return (
    <div className="card">
      {children}
    </div>
  );
}
function App() {
  return (
    <Card>
      <h2>React JS</h2>
      <p>Learn component composition and reuse.</p>
      <button>Explore Course</button>
    </Card>
  );
}
export default App;

The Card component acts as a reusable container. Its child content is supplied by App, allowing the same Card component to display different content in different places.

10. Nested Components in Separate Files

For larger applications, components are often stored in separate files. They can then be imported and nested wherever they are needed.

Example Project Structure:

src/
  components/
    Header.jsx
    Navbar.jsx
    Footer.jsx
  App.jsx
  main.jsx

Header.jsx

function Header() {
  return <header><h1>My Website</h1></header>;
}
export default Header;

Navbar.jsx

function Navbar() {
  return (
    <nav>
      <a href="/">Home</a>
      {" "}
      <a href="/courses">Courses</a>
      {" "}
      <a href="/contact">Contact</a>
    </nav>
  );
}
export default Navbar;

Footer.jsx

function Footer() {
  return <footer>Thank you for visiting.</footer>;
}
export default Footer;

App.jsx

import Header from "./components/Header";
import Navbar from "./components/Navbar";
import Footer from "./components/Footer";

function App() {
  return (
    <div>
      <Header />
      <Navbar />
      <main>
        <h2>Welcome to Our Website</h2>
      </main>
      <Footer />
    </div>
  );
}
export default App;

Each component is exported from its own file and imported into App. The application then nests the imported components within the page layout.

11. Nested Components and Conditional Rendering

A parent component can decide which child component to display based on a condition.

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 (
    <div>
      {isLoggedIn ? <Dashboard /> : <LoginMessage />}
    </div>
  );
}
export default App;

When isLoggedIn is true, React renders Dashboard. Otherwise, it renders LoginMessage. Conditional rendering helps create interfaces that respond to application state and user permissions.

12. Rendering Lists of Nested Components

Components can be nested inside lists by using the JavaScript map() method. Each item should have a stable key.

function CourseCard({ title }) {
  return <li>{title}</li>;
}
function CourseList() {
  const courses = [
    { id: 1, title: "React JS" },
    { id: 2, title: "JavaScript" },
    { id: 3, title: "HTML and CSS" }
  ];
  return (
    <ul>
      {courses.map((course) => (
        <CourseCard key={course.id} title={course.title} />
      ))}
    </ul>
  );
}
function App() {
  return <CourseList />;
}
export default App;

The CourseList component renders a CourseCard for every course in the array. The key helps React identify each list item between renders.

13. Nested Components and Component Reusability

Nested components encourage developers to create reusable UI elements that can be placed in multiple locations.

function Button({ label }) {
  return <button>{label}</button>;
}
function LoginForm() {
  return (
    <form>
      <h2>Login</h2>
      <Button label="Sign In" />
    </form>
  );
}
function SignupForm() {
  return (
    <form>
      <h2>Create Account</h2>
      <Button label="Sign Up" />
    </form>
  );
}
function App() {
  return (
    <div>
      <LoginForm />
      <SignupForm />
    </div>
  );
}
export default App;

The same Button component is reused by LoginForm and SignupForm. Its label changes through props, so the button structure does not need to be duplicated.

14. Important Rule: Do Not Define Components Inside Other Components

Rendering a child component inside a parent is correct. However, defining the child component function inside the parent component function is generally discouraged. React may treat the newly created function as a different component type on each render, which can reset child state and recreate DOM elements.

Incorrect Approach:

function Parent() {
  function Child() {
    return <p>Child Component</p>;
  }
  return <Child />;
}
export default Parent;

Recommended Approach:

function Child() {
  return <p>Child Component</p>;
}
function Parent() {
  return <Child />;
}
export default Parent;

Define component functions at the top level of the module. If the child needs information from the parent, pass that information through props instead of defining the child inside the parent.

15. Difference Between Nested Components and Nested HTML Elements

Feature Nested HTML Elements Nested React Components
Example <div><p>Text</p></div> <Card><Button /></Card>
Purpose Structures content using built-in HTML elements. Combines reusable UI units.
Definition HTML elements are built into the browser. Custom components are defined by the developer or provided by a library.
Data sharing Uses HTML attributes and DOM behavior. Often uses props, children, context, or shared state.
Reusability Elements can be repeated in markup. Components encapsulate reusable UI and logic.

16. Advantages of Nested Components

  • Helps divide complex pages into smaller components.
  • Encourages reusable UI design.
  • Makes the component hierarchy easier to understand.
  • Allows data to flow from parent components to child components through props.
  • Supports consistent styling and behavior.
  • Helps developers test and maintain individual parts of an application.
  • Makes it easier to build layouts, dashboards, forms, product lists, and course pages.

17. Common Mistakes When Using Nested Components

Mistake Problem Solution
Using lowercase custom component names JSX treats lowercase tags as built-in or HTML-like elements. Use capitalized names such as Header or CourseCard.
Forgetting to import a component The component may be undefined or unavailable in the current file. Import the component from the correct module.
Defining a component inside another component The child component may be recreated on each parent render. Define components at module scope.
Passing incorrect props The child may display missing or unexpected values. Check prop names and values.
Forgetting list keys React cannot reliably track list items. Use stable, unique keys for list elements.
Creating excessively deep hierarchies The component structure can become difficult to understand. Keep components focused and the structure clear.
Using one huge parent component Code can become difficult to maintain and reuse. Break the interface into smaller components where appropriate.

18. Best Practices for Nested Components

  • Give every component a clear and meaningful name.
  • Define components at the top level of a module.
  • Keep each component focused on a specific UI responsibility.
  • Pass data to child components using props.
  • Use the children prop when a component needs to wrap arbitrary content.
  • Use stable keys when rendering lists of components.
  • Organize larger projects into folders and separate component files.
  • Avoid unnecessary levels of nesting that make the UI hierarchy hard to follow.
  • Keep rendering logic pure and manage state through React's supported APIs.
  • Reuse existing components instead of repeating the same UI code.

19. Practical Project: Course Website Using Nested Components

Create a simple course website that demonstrates a nested component structure.

Project Requirements:

  1. Create a Header component for the website title.
  2. Create a Navbar component for navigation links.
  3. Create a CourseCard component to display course information.
  4. Create a CourseList component that renders multiple CourseCard components.
  5. Create a Footer component for contact information.
  6. Combine these components inside App.
  7. Pass course titles and descriptions through props.
  8. Use CSS classes to style the components.

Example Code:

function Header() {
  return <header><h1>Learning Portal</h1></header>;
}
function Navbar() {
  return <nav>Home | Courses | Contact</nav>;
}
function CourseCard({ title, description }) {
  return (
    <article>
      <h3>{title}</h3>
      <p>{description}</p>
    </article>
  );
}
function CourseList() {
  return (
    <section>
      <h2>Available Courses</h2>
      <CourseCard
        title="React JS"
        description="Learn to build interactive user interfaces."
      />
      <CourseCard
        title="JavaScript"
        description="Learn the fundamentals of modern JavaScript."
      />
    </section>
  );
}
function Footer() {
  return <footer>Contact our learning team</footer>;
}
function App() {
  return (
    <div>
      <Header />
      <Navbar />
      <CourseList />
      <Footer />
    </div>
  );
}
export default App;

Expected Result: The page displays a header, navigation section, course list containing two course cards, and a footer. The components work together to create a complete page.

20. Interview Questions and Answers

Q1. What are nested components in React?

Answer: Nested components are components rendered inside other components to create a hierarchical and reusable user interface.

Q2. What is a parent component?

Answer: A parent component is a component that renders one or more child components.

Q3. What is a child component?

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

Q4. Can one component render multiple child components?

Answer: Yes. A component can render multiple child components inside its JSX.

Q5. How can a parent pass data to a child component?

Answer: A parent can pass data to a child through props.

Q6. What is the children prop?

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

Q7. Can components be nested across different files?

Answer: Yes. Components can be exported from one file, imported into another, and rendered inside other components.

Q8. Why should component definitions not normally be nested inside other component functions?

Answer: Defining components inside other components can create a new component type on each render, which may reset state and recreate DOM elements. Defining components at module scope avoids this problem.

Q9. What is component composition?

Answer: Component composition is the practice of combining smaller components to build larger UI sections and complete applications.

Q10. What is the benefit of nested components?

Answer: They improve code organization, reusability, readability, and maintainability by dividing the interface into smaller units.

21. Quick Revision Checklist

  • Understand the meaning of nested components.
  • Identify parent and child components.
  • Render one component inside another using JSX.
  • Combine multiple components into a page layout.
  • Pass data using props.
  • Understand and use the children prop.
  • Render lists of child components with stable keys.
  • Import components from separate files.
  • Avoid defining component functions inside other component functions.
  • Build a small project using nested components.

22. Conclusion

Nested Components are an essential part of React JS development. They allow developers to compose a complete user interface from small, reusable components. By understanding parent-child relationships, props, the children prop, component hierarchy, and best practices for defining components, developers can build React applications that are organized, scalable, and easier to maintain.

Explore the JustAcademy React JS Training Course to learn more about React development.

To explore a course demonstration, visit Register for React JS Course Demo.

23. Official React Documentation

Previous Next
whatsapp