DEV Community

almokhtar bekkour
almokhtar bekkour

Posted on

create a modal component with stimulus js

Here is an example of how you could create a modal component with Stimulus.js:

// controllers/modal_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
static targets = ["overlay", "content", "closeButton"]

open() {
this.overlayTarget.classList.add("is-active")
this.contentTarget.classList.add("is-active")
}

close() {
this.overlayTarget.classList.remove("is-active")
this.contentTarget.classList.remove("is-active")
}

toggle() {
this.overlayTarget.classList.toggle("is-active")
this.contentTarget.classList.toggle("is-active")
}

// Event handler for the "click" event on the close button
closeButtonClick(event) {
event.preventDefault()
this.close()
}
}

This modal component uses a few classes to control its visibility:

is-active: shows the modal
is-inactive: hides the modal
Enter fullscreen mode Exit fullscreen mode

To use this component in your HTML, you would need to add the following markup:

<a href="#">Close</a>
Enter fullscreen mode Exit fullscreen mode

This will create a modal with an overlay, a content area, and a close button. When the close button is clicked, it will call the closeButtonClick method on the modal controller, which will hide the modal.

Top comments (0)