LWC: Apply Spread Properties To Child Components

  • LWC: Propagate a set of properties to a child component by utilizing the spread syntax.
  • The lwc:spread functionality allows elements to dynamically accept an object as properties during runtime.
  • This directive accepts a singular object.
  • This directive accepts a singular object.
  • Within your child component, incorporate these properties in your template.
  • Utilize the @api decorator to make your properties accessible to the parent component.
  • Note that lwc:spread consistently takes precedence, superseding any properties explicitly declared in the template. It’s important to highlight that only one instance of lwc:spread can be employed within a directive.

Example Below:

Parent LWC Component:

<template>
    <lightning-card title="LWC Spread Properties">
        <c-child lwc:spread={childPropsData}></c-child>
    </lightning-card>
</template>
import { LightningElement } from 'lwc';

export default class App extends LightningElement {
    childPropsData = { name: "CloudHAK", country: "INDIA" };
}

Child LWC Component:

<template>
    {name} &nbsp; {country}
</template>
import { LightningElement,api } from 'lwc';

export default class Child extends LightningElement {
    @api name;
    @api country;
}

Feel free to give our post a thumbs up and save this blog for future reference in your learning journey. We value your suggestions and welcome any feedback; please share your thoughts in the comment box. Happy coding, and remember, sharing is caring!