In Lightning Web Components (LWC), sometimes we need to pass value from parent to child lwc and child to parent to make our code less complex , well structured and reusable.
In the Lightning Web Component, we have different ways to communicate between Lightning Web Components.
The following are the ways:
- Parent to Child Communication
- Child to Parent Communication
In this blog post , we will discuss about the Parent to Child and Child to Parent Communication in Lightning Web Components (LWC).
Table of Contents
ToggleParent to Child in Lightning Web Components
As its name suggests, we need to pass the message from parent component to child component. The parent component can control the child component by passing the message to child component. Thus , it can be achieved by using @api decorator. To expose a public property, decorate a field with @api
( Public properties define the API for a component).
We need to call the child component by adding in HTML using <c-child-comp></c-child-comp> in this way.
How to Pass value from parent component to child component in LWC
- Define a Public Property in the Child Component-A public property in LWC is marked with the @api decorator. This makes the property accessible to the parent component.
- Pass Data from Parent to Child- The parent component uses HTML attributes to pass data to the child component
The @api decorator in Lightning Web Components is reactive, so whenever the parent component updates a value , the child component automatically re-renders to display the updated value.
Let’s discuss an example of Parent to Child communication in Lightning Web Components step by step :-
Step 1 – Create the Child Component named childComponent.
Below are the code snippet –
childComponent.html
<template>
<div>
<p>Message from Parent: {message}</p>
</div>
</template>
childComponent.js
import { LightningElement, api } from 'lwc';
export default class ChildComponent extends LightningElement {
@api message; // Public property to receive data
}
childComponent.js-meta.xml
<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>61.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>
Step 2: Create the Parent Component named parentComponent
parentComponent.html
<template>
<lightning-card title="Parent Component">
<p>This is the parent component.</p>
<c-child-component message={parentMessage}></c-child-component>
</lightning-card>
</template>
parentComponent.js
import { LightningElement } from 'lwc';
export default class ParentComponent extends LightningElement {
parentMessage = 'Dynamic Message from Parent';
}
parentComponent.js-meta.xml
<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>61.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
<target>lightning__RecordPage</target>
<target>lightning__RecordAction</target>
</targets>
</LightningComponentBundle>
Here, the child component will display the value of parentMessage, which can be updated dynamically.
Here, we pass value from parent to child lwc ,deploy only the parent component and put it on UI and this is how it will be displayed.
Points to remember
- Use @api in the child component for public properties.
- Data passed from parent to child is one-way. The child can’t modify the parent’s data directly
- You dont need to deploy the child component separately.
- You do not need to set the child component’s
isExposed
attribute totrue
.
Benefits of Parent-to-Child Communication in LWC
- Promotes Reusability : Child component can be used again and again as per need in multiple components.
- Real-Time Updates : If the parent component’s data changes, the child automatically reflects those changes without additional code.
- Improves Code Organization : The code becomes more structured and easy to understand.
- Easier Scalability : We can create multiple child components and pass data to them from the parent without disturbing the existing functionality.
Child to Parent Communication in Lightning Web Component
As its name suggests, we need to pass the message from child component to parent component. The child component notifies its parent about an event or passes data back, this is achieved using custom events.
How to Implement Child to Parent Communication in Lightning Web Components
In this part , we will discuss how to pass data from child to parent step by step:
Step 1 : Steps to Implement Child-to-Parent Communication
-The child component uses this.dispatchEvent()
for firing an event.
Step 2 : Add an Event Listener in the Parent Component
-The parent component listens for the event and handles it.
Let’s discuss an example of Child to Parent communication in Lightning Web Components:
Below are the code snippets –
childComponent.html
<template>
<div>
<p>Greeting from Parent: {greeting}</p>
<lightning-button
label="Send Message to Parent"
onclick={sendMessageToParent}>
</lightning-button>
</div>
</template>
childComponent.js
import { LightningElement, api } from 'lwc';
export default class ChildComponent extends LightningElement {
@api greeting; // Public property to receive data from parent
sendMessageToParent() {
// Dispatching a custom event with a message to the parent
const event = new CustomEvent('messagefromchild', {
detail: { message: 'Hello Parent, from Child!' }
});
this.dispatchEvent(event);
}
}
- In this child component,
messagefromchild
is the event name. - The
detail
object contains the data sent to the parent.
parentComponent.html
<template>
<lightning-card title="Parent Component">
<p>Message from Child: {childMessage}</p>
<c-child-component
greeting={parentGreeting}
onmessagefromchild={handleMessageFromChild}>
</c-child-component>
</lightning-card>
</template>
parentComponent.js
import { LightningElement } from 'lwc';
export default class ParentComponent extends LightningElement {
parentGreeting = 'Hello Child!'; // Data sent to child
childMessage = ''; // Data received from child
handleMessageFromChild(event) {
// Update the message based on child's custom event
this.childMessage = event.detail.message;
}
}
This is how it will be displayed :
- When the button in the child component is clicked then it dispatches a custom event (
messagefromchild
) with the message in thedetail
object. - Now check the image ,how it is looking now after clicking the button it is showing the message that is received from the child component.
Benefits of Child-to-Parent Communication in Lightning Web Components
- Improves Component Interactivity : The child component will notify the parent component about user actions, like button clicks or form submissions.
- Keeps Components Decoupled : The child component doesn’t directly modify the parent’s state but communicates via events.
- Enables Dynamic Data Flow : Custom events allow real-time updates between the child component and parent component.
Summary
In this blog, we have explored the two important ways to communicate in Lightning Web Components (LWC) – Parent to Child Communication and Child to Parent Communication.
Parent to Child Communication : Data flows from the parent component to child component using public properties marked with @api
decorator. This way you can control the child component’s behavior by passing dynamic data from the parent.
Child to Parent Communication : The child component notifies the parent component about actions or shares data using custom events.
You can deepen your understanding of Lightning Web Components by exploring our comprehensive course on LWC.
You can explore more about Lightning Web Components through this video and check out our latest blogs on our websites for additional knowledge about salesforce.