How to Nest Components in React: Simple Guide with Examples
In React, you nest components by including one component inside another using JSX tags like
<ChildComponent />. This lets you build complex UIs by combining smaller, reusable pieces called components.Syntax
To nest components in React, you import the child component and then use it inside the parent component's JSX by writing it as a tag. The child component can be self-closing if it has no children.
- ParentComponent: The component that contains other components.
- ChildComponent: The component nested inside the parent.
- JSX tags: Use
<ChildComponent />to include the child.
jsx
import React from 'react'; function ChildComponent() { return <p>This is the child component.</p>; } function ParentComponent() { return ( <div> <h1>Parent Component</h1> <ChildComponent /> </div> ); } export default ParentComponent;
Output
Parent Component
This is the child component.
Example
This example shows a parent component that nests two child components. Each child displays its own message. This demonstrates how nesting helps organize UI parts clearly.
jsx
import React from 'react'; function Header() { return <header><h2>Welcome to My Site</h2></header>; } function Footer() { return <footer><p>© 2024 My Site</p></footer>; } function Page() { return ( <div> <Header /> <main> <p>This is the main content area.</p> </main> <Footer /> </div> ); } export default Page;
Output
Welcome to My Site
This is the main content area.
© 2024 My Site
Common Pitfalls
Common mistakes when nesting components include:
- Forgetting to import the child component before using it.
- Using lowercase names for components, which React treats as HTML tags instead of components.
- Not closing the component tag properly (missing
/>in self-closing tags).
jsx
/* Wrong: missing import and lowercase component name */ function parent() { return <childcomponent />; // React treats this as HTML tag, not component } /* Right: import and proper capitalization */ import ChildComponent from './ChildComponent'; function Parent() { return <ChildComponent />; }
Quick Reference
- Always start component names with a capital letter.
- Import child components before using them.
- Use JSX tags to nest components inside others.
- Self-close tags if no children:
<Child />. - Use props to pass data between nested components.
Key Takeaways
Nest components by including them as JSX tags inside other components.
Always capitalize component names so React recognizes them as components.
Import child components before using them in a parent component.
Use self-closing tags for components without children.
Nesting helps build complex UIs from small, reusable pieces.