How to send data from parent to child in LWC

In all the modern JavaScript frameworks data by default flows from top to bottom.

Lightning Web Components is not an exception.

For this to happen there are a few guidelines that we need to follow. Just because we have embed a child component in parent component, child component is not going to accept the data from parent.

Once after the properties are created we need to decorate the properties in child component using a decorator which is @api.

You can think of @api as public access specifier in Apex.

If we make a property @api the parent component can push data to the child component.

import { LightningElement, api } from "lwc";

export default class ChildComponent extends LightningElement {
  @api
  name = "Teja"; 

  handleClick() {
    /* I cannot do this
	 * this.name = 'updated name'
     */     
  }
}
childComponent.js

Markup in the Parent component is going to look like this!


<template>

<c-child-component name="Krishna Teja"></c-child-component>
</template>
parentComponent.html

However, there are a few limitations

  • Once a property in the child component is decorated with @api, no matter what, child component cannot mutate the content of that property.
  • If child component wants to update the content of the property, it has to send a request to the parent along with the new value (using events) and parent is going to push the new value to the child component.
  • Properties in the child component JavaScript file follows camel casing where as the kebab casing is used in the parent component to push the data down.

if the property in the child component is taxExemptedBalance then in the parent component the mark-up is going to look like this.

<c-child-component tax-exempted-balance="100000"></c-child-component>
Passing data to child component

Hope this is useful!