Parent-Child Relationship in Component Composition (Live Playground)
Component composition is an essential aspect of building modular and reusable components in React. The parent-child relationship is the cornerstone of this approach. In this tutorial, we'll explore the parent-child relationship with sample code and simple explanations.
Creating Parent and Child Components
To demonstrate the parent-child relationship, let's create two components: a Parent
component and a Child
component.
import React from 'react';
function Parent() {
return (
<div>
<h1>I am the Parent Component</h1>
<Child />
</div>
);
}
function Child() {
return <p>I am the Child Component</p>;
}
export default Parent;
In this example, the Child
component is rendered inside the Parent
component, establishing a parent-child relationship.
Passing Data from Parent to Child
One of the main advantages of the parent-child relationship is the ability to pass data from the parent component to the child component using props.
import React from 'react';
function Parent() {
const message = 'Hello from Parent';
return (
<div>
<h1>I am the Parent Component</h1>
<Child text={message} />
</div>
);
}
function Child(props) {
return <p>{props.text}</p>;
}
export default Parent;
In this example, we pass the message
variable from the Parent
component to the Child
component using the text
prop.
Callback Functions for Child-to-Parent Communication
To communicate from the child component to the parent component, you can pass a callback function as a prop.
import React, { useState } from 'react';
function Parent() {
const [message, setMessage] = useState('No message received.');
const handleMessage = text => {
setMessage(`Message from Child: ${text}`);
};
return (
<div>
<h1>I am the Parent Component</h1>
<p>{message}</p>
<Child onSendMessage={handleMessage} />
</div>
);
}
function Child(props) {
const handleClick = () => {
props.onSendMessage('Hello from Child');
};
return <button onClick={handleClick}>Send Message</button>;
}
export default Parent;
In this example, we pass the handleMessage
function from the Parent
component to the Child
component using the onSendMessage
prop. The Child
component can then call this function to communicate with the Parent
.
Conclusion
Understanding the parent-child relationship in React component composition is crucial for creating modular and reusable components. By creating parent and child components, passing data from parent to child using props, and using callback functions for child-to-parent communication, you can build more maintainable and scalable applications.