DEV Community

Lewis Sparlin for KnownDecimal

Posted on • Originally published at knowndecimal.com

4 2

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 "https://unpkg.com/@hotwired/stimulus/dist/stimulus.js"
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
</button>
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 "https://unpkg.com/@hotwired/stimulus/dist/stimulus.js"
const customSchema = {
 ...defaultSchema,
 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
</button>
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!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

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

Okay