Stimulus Use
I was getting rather annoyed when using modals with stimulus, especially when it came to actually closing them. I didnt like the way I wrote the general function to close the modals so I decided to refactor it. In doing so I came across a package that would solve it all. The package is called stimulus-use (https://github.com/stimulus-use/stimulus-use). It enables new lifecycle behaviors to your stimulus controllers. Now I can close my modals like so, instead of trying to check if my modal has a click event outside of it:
import { Controller } from 'stimulus'
import { useClickOutside } from 'stimulus-use'
export default class extends Controller {
connect() {
useClickOutside(this)
}
clickOutside(event) {
event.preventDefault()
this.modal.close()
}
}