DEV Community

Lewis Sparlin for KnownDecimal

Posted on • Originally published at

Customize Stimulus Attributes, Avoid Conflicts

Stimulus is all about giving you front-end functionality with minimal JavaScript fuss and weight, but in certain cases, its data attributes can run into conflict with other libraries. I've recently made a pull request to add this to their docs, but for anyone else who's encountered this conflict, a little reconfiguration of the library's schema can keep your Stimulus implementation conflict-free.

Outside of a build system, Stimulus is initialized as documented in their handbook:

import { Application } from ""
window.Stimulus = Application.start()
Enter fullscreen mode Exit fullscreen mode

Stimulus uses HTML data attributes to target and add listeners to elements on the page. In Stimulus if you wanted a button to show a modal, you might write something like this:

<button data-action="modal#show">
 Set up your profile
Enter fullscreen mode Exit fullscreen mode

If you were to include Stimulus in a project that already had several JavaScript libraries, you may encounter what I encountered. The HTML attribute data-action was already being monitored by another library. Fortunately, after reading through their code I discovered there are parameters that can be passed to Application. The data attributes Stimulus looks for can be customized by passing a different "schema".

import { Application, defaultSchema } from ""
const customSchema = {
 actionAttribute: 'data-stimulus-action'
window.Stimulus = Application.start(document.documentElement, customSchema)
Enter fullscreen mode Exit fullscreen mode

This would allow you to create Stimulus event listeners using your custom attribute:

<button data-stimulus-action="modal#show">
 Setup your profile
Enter fullscreen mode Exit fullscreen mode

Stimulus is a great tool that gives you a lot of power on the front end for very little overhead— if you'd like to see a blog series from me to get a thorough introduction to the library, let us know!

Top comments (0)