Lightning Web Component

How to Create a LWC Modal/Popup in Salesforce

An LWC Modal is helpful to improve the user experience by providing context-specific information or actions without disrupting the application flow.

In this article, we will see how to create a Modal/Popup in a Lightning Web Component with reduced code and close the modal when clicking outside.

How to Create a LWC Modal/Popup

LWC Modal Component

Let's start with the component's HTML, which will be where we have our modal. Here are some things to know:

<lightning-button label="Enable Modal" data-action="open" onclick={handleModal}></lightning-button>
<div if:true={modalOpen} class="backdrop" data-action="close" onclick={handleModal}></div>

<!-- MODAL -->
<section if:true={modalOpen} class="modal">
    <!-- HEADER -->
    <header class="slds-modal__header">
        <h2 class="slds-text-heading_medium slds-hyphenate">Title of the Modal</h2>

    <!-- BODY -->
    <main class="slds-modal__content slds-p-around_medium">
      <p>This is the body message of the Modal</p>

    <!-- FOOTER -->
    <footer class="slds-modal__footer">
      <lightning-button label="Cancel" data-action="close" onclick={handleModal}></lightning-button>

The Javascript of our component is basic. Here, we will modify some variables to handle the modal.

import { LightningElement } from 'lwc';
export default class PublisherComponent extends LightningElement {
    modalOpen = false;
        const action = e.currentTarget.dataset.action;
        if(action == 'open') this.modalOpen = true;
        else if(action == 'close') this.modalOpen = false;

Finally, here is the CSS with the styles of our component.

.backdrop {
    z-index: 99;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    backdrop-filter: blur(2px);
    background-color: #0000004a;
.modal {
    z-index: 100;
    position: absolute;
    min-width: 40rem;
    width: fit-content;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
If the modal's background is not working correctly, modify the z-index on both classes. The .modal always has to be higher than the .backdrop
Demo in how to Create a LWC Modal/Popup