Andy Tran

LWC : Share Data Between Parent and Child Components

by | 21 Oct, 2022 | Salesforce | 1 comment

LWC - Share Data Between Parent and Child Components

Introduction to LWC

Salesforce uses Lightning Web Component (LWC), a quick and lightweight tool, to construct Lightning Components. Performance and reuse are advantages of component-based development.

You will undoubtedly encounter a situation where you need to transfer data between components if they are linked to one another by a relationship of some kind, such as a parent-child relationship.

Data can be shared from a parent to a child and a child to a parent.


Sharing of data in LWC
File structure

    • parentLWC
      • parentLWC.html
      • parentLWC.js
    • childLWC
      • childLWC.html
      • childLWC.js

Share the data from parent to child
We must make class property public in order to accept data from the parent. All class properties are reactive and private by default.

“Private” describes a property as being solely visible to the component in which it is declared and not accessible to any other components in the DOM.

“Reactive” indicates that the property is being monitored by the Lightning Framework, and if it changes, the Framework redraws the relevant portion of the DOM. Refer to the Lifecycle Hooks in LWCblog post to learn more about the Lightning Framework and how rerendering functions.

Question is: how can we make a class property public?

It’s easy; all we need to do is decorate our property with the “api” keyword, which is offered by the lwc library This will make our property public, and we can then change its value from the parent component.

The below code shows how we make class property public.

childLWC.JS


import { LightningElement, api} from 'lwc';
export default class ChildLWC extends LightningElement {
    // reactive and public
    @api val;
}

The following code demonstrates how to set the value of a public class property in a child component from a parent component:

parentLWC.HTML


<template>
    <c-child-l-w-c val={sliderValue}></c-child-l-w-c>
</template>

parentLWC.JS


import { LightningElement } from 'lwc';
export default class ParentLWC extends LightningElement {  
    // reactive and private
    sliderValue = 45;  
}

Share the data from child to parent
We must utilize a custom event that the parent component will listen to in order to send data from the child to the parent.

In the sliderValChange method of the childLWC.js file, we have created a custom event with the name “childsliderevent” which provides data inside the key “detail”.

childLWC.html


lt;template>
    <div style="border:2px solid crimson; margin: 10px;">
        <b>HELLO, I'am Child Component.</b>
        <lightning-slider style="margin: 10px;" label="Volume" value={val} onchange={sliderValChange}>
        </lightning-slider>
    </div>
</template>

childLWC.js


import { LightningElement, api} from 'lwc';
export default class ChildLWC extends LightningElement {
    // reactive and public
    @api val;
   
    // call this method on any event.
    sliderValChange(event){
        // CUSTOM event
        const valueChangeEvent = new CustomEvent('childsliderevent',
        {
            // attribute name: {key: value}
            detail: {sliderValue: event.target.value}
        }
        );
        this.dispatchEvent(valueChangeEvent);
    }
}

How do we listen to custom events from the parent component?

Simply add “on” before the name of the custom event—in this case, “onchildsliderevent”—and add this as an attribute when calling childLWC from parentLWC.

When a childLWC fires a childsliderevent, the parentLWC that is listening to the event receives the event and calls the handleSliderChange method in the parentLWC. Refer Fig-2.


Listening to custom event from parent components
parentLWC.HTML


<template>
  <c-child-l-w-c val={sliderValue}
           onchildsliderevent={handleSliderChange}>
  </c-child-l-w-c>
</template>

parentLWC.JS

import { LightningElement } from 'lwc';
export default class ParentLWC extends LightningElement {    
    handleSliderChange(event){
        //child data
        console.log(event.detail.sliderValue);
    }    
}

Project
Let’s use a simple project to understand how it functions.

The one we’re going to create is shown as Fig-3 below.
Crimson border – represents the child component.
Black border – represents the parent component.

To achieve:

  • Synchronize the parent and child component’s data.
  • Able to change the value of the slider in child by changing the input field from the parent.
  • Able to change the value of input field in parent by changing value of slider from child.


parent and child component’s data
childLWC.HTML

<template>
    <div style="border:2px solid crimson; margin: 10px;">
        <b>HELLO, I'am Child Component.</b>
        <lightning-slider style="margin: 10px;" label="Volume" 
             value={val} onchange={sliderValChange}>
        </lightning-slider>
    </div>
</template>

childLWC.JS

import { LightningElement, api} from 'lwc';

export default class ChildLWC extends LightningElement {
    // reactive and public
    @api val;
   
    // call this method on any event.
sliderValChange(event){
        // CUSTOM event
        const valueChangeEvent = new CustomEvent('childsliderevent',
        {
            // attribute name: {key: value}
            detail: {sliderValue: event.target.value}
        }
        );
        this.dispatchEvent(valueChangeEvent);
    }
}

parentLWC.html


<template>
    <div class={bkColor} style="border:2px solid black; padding: 10px;">
        <b>Parent Component</b>
        <lightning-input type="number" label="Enter a number" name="sliderValue" value={inputValue}
        onchange={handleChange} data-id="test">
        </lightning-input>
        <c-child-l-w-c val={sliderValue} onchildsliderevent={handleSliderChange}></c-child-l-w-c>
    </div>
</template>

parentLWC.JS


import { LightningElement } from 'lwc';

export default class ParentLWC extends LightningElement {  
    // reactive and private
    sliderValue = 45;
    inputValue;
   
    handleChange(event){
        this[event.target.name] = event.target.value;
    }
   
    handleSliderChange(event){
        //child data
        this.inputValue = event.detail.sliderValue;
    }
}

We appreciate your attention to our blog and are certain that our concepts and methodologies offer significant value. If your company is in need of Salesforce-related services, we are delighted to offer our specialized expertise. Erudite Works is widely acknowledged as a leading Salesforce Service Cloud consultant, and our team of consultants has successfully assisted businesses of all sizes, understanding their unique operational requirements, providing expert technical and procedural advice, tailoring modules to their specific needs, and seamlessly implementing CRM solutions to streamline integrations. If you would like to learn more about our services, please feel free to contact us.

Also Read: Start LWC Testing using Jest

Share this article...

1 Comment

  1. Manankumar Choraria

    Can you please give som use cases, when we can pass data from parent to child or child to parent?

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.