Lightning Modal in LWC
The LWC provides a lightning modal feature to show specific content in the modal popup. In most cases, the developer uses a custom modal popup instead of a lightning modal. Lightning modal reduces the complexity of conditionally rendering the popup in the component.
Step 1: First, create a LWC component that includes the modal popup feature.
modalPop.html
<template>
<lightning-modal-header label=’lightning modal’ >
<span>
<lightning-icon icon-name=”action:approval”
style=”zoom:60%”>
</lightning-icon>
</span>
</lightning-modal-header>
<lightning-modal-body>
<div>
<div>
<div style=”margin-left:1cm;margin-right:1cm”>
<span
style=”font-size:15px;”>Lightning modal popup
</span>
</div>
</div>
</div>
</lightning-modal-body>
<lightning-modal-footer>
<lightning-button label=”OK” variant=”brand”
onclick={handleOkay}></lightning-button>
</lightning-modal-footer>
</template>
modalPop.js
import { api } from ‘lwc’;
import LightningModal from ‘lightning/modal’;
export default class ModalPopup extends LightningModal {
handleOkay() {
this.close(‘okay’);
}
}
Step 2: Now create your target component that you are going to work with in the modal popup.
targetCmp.html
<template>
<lightning-button
onclick={handleClick}
aria-haspopup=”dialog”
label=”Open My Modal”>
</lightning-button>
<p>Result: {result}</p>
</template>
Step 3: You have to import the modal pop component into the target component as mentioned.
below, then only we can use the modal mopup feature.
TargetCmp.js
import { LightningElement } from ‘lwc’;
import MyModal from ‘c/modalPopup’;
export default class ModalPopup2 extends LightningElement {
result;
async handleClick() {
this.result = await MyModal.open({
size: ‘small’,
description: ‘Accessible description of modal\’s purpose’,
label:’test’,
});
}
}
Note: If we show the modal popup in the component, then we access the modal popup result in the target component.
- If you click OK, then the result will be okay.
- If you click the x icon, then the result would be undefined.
We can work with these values on the target component.
This lightning modal has only three layout sizes:small, medium, and large.
If you want to customize the modal window size, then go with a custom modal popup.
Output:
From the target component:

