React applications are built using components. Components can be connected to each other, and one component can pass data to another component.
What is a Child Component?
- A child component is a component that is rendered inside another component.
- The component that contains the child is called the parent component.
For example:
function BlogPost() {
return <h2>Introduction to React</h2>;
}
function App() {
return (
<div>
<h1>My Blog</h1>
<BlogPost />
</div>
);
}
Here:
-
Appis the parent component. -
BlogPostis the child component. -
<BlogPost />is used insideApp.
The relationship is:
App (Parent)
↓
BlogPost (Child)
What are Props?
Props stands for Properties.
Props are used to pass data from a parent component to a child component.
Props are passed using attributes.
Example
function BlogPost(props) {
return <h2>{props.title}</h2>;
}
function App() {
return (
<div>
<BlogPost title="Introduction to React" />
</div>
);
}
Here:
<BlogPost title="Introduction to React" />
The parent component App passes the value:
Introduction to React
to the child component BlogPost.
The child receives this data through:
props.title
So the flow is:
Parent Component
|
| title="Introduction to React"
↓
Child Component
|
↓
props.title
Why Do We Use Props?
Props are mainly used to make components reusable.
For example, instead of creating a separate component for every blog post, we can create one BlogPost component and pass different data to it.
function BlogPost(props) {
return (
<article>
<h2>{props.title}</h2>
<p>{props.description}</p>
</article>
);
}
function App() {
return (
<div>
<h1>My Blog</h1>
<BlogPost
title="Introduction to React"
description="React is a JavaScript library for building user interfaces."
/>
<BlogPost
title="Understanding JavaScript"
description="JavaScript is used to create interactive web applications."
/>
</div>
);
}
export default App;
Here, the same BlogPost component is reused twice with different data.
Output
My Blog
Introduction to React
React is a JavaScript library for building user interfaces.
Understanding JavaScript
JavaScript is used to create interactive web applications.
The component remains the same, but the data changes through props.
Props are read-only.
A child component should not directly change the props it receives from its parent.
For example:
function BlogPost(props) {
return <h2>{props.title}</h2>;
}
Props Can Contain Different Types of Data
<BlogPost
title="React"
views={100}
isPublished={true}
/>
Here:
-
title→ String -
views→ Number -
isPublished→ Boolean
Props can also pass arrays, objects, and even functions.
Conclusion
A child component is a component rendered inside a parent component. Props provide a way for the parent component to send data to its child component.
The basic flow is:
Parent Component
↓
Props
↓
Child Component
↓
Display Data
Props make React components reusable, flexible, and easier to manage.
Top comments (0)