Stimulus Naming Conventions
Stimulus is a JavaScript framework designed for enhancing HTML. Adhering to its naming conventions ensures seamless integration and makes your code more maintainable.
Controller Naming
The controller filename should be in snake_case with the suffix _controller.js:
hello_controller.js
user_profile_controller.js
Stimulus connects elements using the data-controller attribute:
<div data-controller="hello">
<!-- Controller content -->
</div>
Action Naming
Action names should be in camelCase. Actions are JavaScript functions that Stimulus can access within the controller context:
// hello_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
greetMe() {
// Action implementation
}
}
In HTML, actions are specified using the data-action attribute:
<button data-action="click->hello#greetMe">Click Me</button>
Target Naming
Target names should be in camelCase. Stimulus identifies target elements using the data-target attribute:
// hello_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ["bannerElement", "inputField"]
greetMe() {
this.bannerElementTarget.textContent = "Hello World!"
}
}
In HTML:
<div data-controller="hello">
<h1 data-hello-target="bannerElement"></h1>
<input data-hello-target="inputField" />
<button data-action="click->hello#greetMe">Click Me</button>
</div>
Complete Example
Here's a complete example demonstrating all naming conventions:
// app/javascript/controllers/hello_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ["bannerElement", "messageInput"]
connect() {
console.log("Hello controller connected")
}
greetMe() {
const message = this.messageInputTarget.value || "Hello World!"
this.bannerElementTarget.textContent = message
}
clearMessage() {
this.bannerElementTarget.textContent = ""
this.messageInputTarget.value = ""
}
}
<!-- app/views/pages/hello.html.erb -->
<div data-controller="hello">
<h1 data-hello-target="bannerElement">Initial Message</h1>
<input
type="text"
data-hello-target="messageInput"
placeholder="Enter a message"
/>
<button data-action="click->hello#greetMe">Greet</button>
<button data-action="click->hello#clearMessage">Clear</button>
</div>
Key Points
- Controllers:
snake_casewith_controller.jssuffix - Actions:
camelCasemethod names - Targets:
camelCasein both JavaScript and HTML - Data attributes: Use
data-controller,data-action, anddata-{controller}-target
Conclusion
Following Stimulus naming conventions ensures that your controllers, actions, and targets work together seamlessly. These conventions are not just stylistic—they're required for Stimulus to properly connect your JavaScript to your HTML.