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.

API Trace View

Struggling with slow API calls? đź‘€

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay