Modal Windows
Open a modal window in response to a user action, such as clicking a button or link. The modal blocks interaction with everything else on the page until the user acts upon or dismisses the modal.
The lightning/modal
module provides the LightningModal
component to create a modal window that overlays the current window.
LightningModal
implements the SLDS modals blueprint.
Unlike most base components, when you use this component you don’t add a <lightning-modal>
tag to your component template or extend LightningElement
. There is no lightning-modal
component. Instead, you create a modal by extending LightningModal
.
The LightningModal
component provides helper components for specifying the modal content. Use the required lightning-modal-body
component to provide the main content displayed in the modal. Use the optional lightning-modal-header
component to add a title to the top of the modal, and the optional lightning-modal-footer
component to add a footer to the bottom.
To create a modal component, import LightningModal
from lightning/modal
. Don’t import from LightningElement
.The component has access to the normal LWC resources as well as the special container, helper components, methods, and events of the lightning/modal
module.
Let’s create a simple modal called myModal
that looks like this.
Here’s the JavaScript for myModal
. It imports only api
, not LightningElement
, from lwc
. Instead, it imports LightningModal
and extends LightningModal
to its own class. It defines an options
array to accept content that’s provided when the modal is opened by another component. The handleOptionClick
function handles button clicks in the modal. When the user clicks the Option 1 or Option 2 button, this.close(id)
returns the option that they chose and the modal closes.
Here’s the myModal.html
template, which includes a header and the modal body.
Here’s a component myApp
that opens the myModal
component when you click the Open My Modal button. It displays the result returned when the modal’s Option 1 or Option 2 buttons are clicked.
Here’s the myApp
template.
The component myApp.js
imports MyModal
from the myModal
component. The button handler opens the myModal
component using the component’s open
method and provides data to be used in the modal’s options
property.
The result
value is returned from MyModal
and displayed by the myApp
component.
For more details about using LightningModal
, see the Component Reference.
The lwc-recipes repo has miscModal
and myModal
components that demonstrate the use of LightningModal
.
See Also
- Component Reference:
lightning-modal-body
- Component Reference:
lightning-modal-header
- Component Reference:
lightning-modal-footer