How to send data from parent to child in LWC

Let's look at how to sned data from the parent to the child component 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 embeded a child component in the parent component, the child component is not going to accept the data from the 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 {
  name = "Teja"; 

  handleClick() {
    /* I cannot do this
       * = 'updated name'
<!-- Parent Component -->

<c-child-component name="Krishna Teja"></c-child-component>

However, there are a few limitations

  • Once a property in the child component is decorated with @api, no matter what, the child component cannot mutate the content of that property.
  • If the 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 the 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>

Hope this is useful!