How to send data from the Parent component to the Child component in LWC

|
| By Navneet Negi

The Lightning Web Component (LWC) is widely used over the salesforce platform to build components that can work dynamically and are a combination of Custom HTML and modern JavaScript. Depending on the need, they can be displayed over Home Page, Record Page, App Page, and many more. In this post, we’re going to show a parent component that will send the value to its child component and also know the importance of @api annotation in LWC.

Step 1: Create a Child Component.

HTML file:
<template>
<div style="background : white; border : 1px dotted green; margin-top:20px; margin-bottom:20px">
<h1 align="center"> <b> Child Component </b> </h1>
<p> <b> Value received from Parent Component : {valueFromParentCmp} </b> </p>
</div>
</template>

JS controller:
import { LightningElement, api } from 'lwc';
export default class ChildComponent extends LightningElement {
@api valueFromParentCmp;
}

The @api here exposes the variable’s public properties for it to be available for the parent component to access or say set the value for this variable.
Also, make sure to expose the component by making the changes in the js-meta.xml file so that we can view it in our Salesforce org.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>56.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>
lightning__HomePage
</target>
</targets>
</LightningComponentBundle>

Step 2: Create a Parent Component.
HTML file:
<template>
<div style="background : white; border : 1px solid black">
<h1 align="center"> <b> Parent Component </b> </h1>
<lightning-input label="Enter Value to be sent to the Child Component : " onchange={handleChange}>
</lightning-input>
<c-child-component value-from-parent-cmp = {value}> </c-child-component>
</div>
</template>

Note: Use the Camel Case naming convention to name your component and also your api decorated variable so that it can be called in the parent component using hyphens.

JS Controller:
import { LightningElement } from 'lwc';
export default class ParentComponent extends LightningElement {
value;
handleChange(event){
this.value = event.target.value;
}
}

After displaying the Parent component in our Salesforce org, we’ll be able to see the value passing from the Parent component to the Child component like this:
Component in LWC

Leave a Reply

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