Monday, September 16, 2024

What is Shadow DOM in LWC?

In Lightning Web Components (LWC), encapsulation refers to the isolation of a component’s internal structure, styles, and behavior from the rest of the application. This is primarily achieved using the Shadow DOM, which ensures that the component’s logic remains self-contained and unaffected by external factors, allowing it to function independently.The styles defined inside a component are scoped to that component and do not affect other components or the global application.The component’s internal DOM is hidden from the outside world, ensuring that its structure and behavior cannot be directly manipulated by external code.

In the below example, Shadow DOM in Lightning Web Components (LWC) is used to encapsulate the styles and DOM structure of the parent and child components, preventing style leakage between them:

The parent component (`ParentShadowDOM`) defines a `<p>` tag with blue text and large font, which applies only to the parent due to Shadow DOM encapsulation.

The child component (`childLWCComp`) has its own `<p>` tag styled with red text and small font.

Since both components use Shadow DOM, the styles of the parent component do not affect the child component, and vice versa, ensuring complete isolation of their DOM structure and styles. This maintains a clear separation between the two components, allowing each to have its own independent styling and behavior.

parentShadowDOM.html

<template>

    <div><p>I am parent comp</p></div>

    <div>

  <c-child-lwc-comp></c-child-lwc-comp>

    </div>

</template>

parentShadowDOM.js

import { LightningElement } from 'lwc';

export default class ParentShadowDOM extends LightningElement {}

parentShadowDOM.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>61.0</apiVersion>

    <isExposed>false</isExposed>

</LightningComponentBundle>

parentShadowDOM.css

p{

    color: blue;

    font-size: large;

}

childLWCComp.html

<template>

    <div><p>I am child comp</p></div>

</template>

childLWCComp.js

import { LightningElement } from 'lwc';


export default class ChildLwcComp extends LightningElement {}

childLWCComp.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>61.0</apiVersion>

    <isExposed>false</isExposed>

</LightningComponentBundle>

childLWCComp.css

p{

    color: red;

    font-size: small;

}

Let us now preview this component for testing by adding it in Aura App as shown below.

<aura:application>

<c:parentShadowDOM></c:parentShadowDOM>

</aura:application>


What is Shadow DOM in LWC?

No comments:

Post a Comment