Catalog / Stimulus.js Cheatsheet
Stimulus.js Cheatsheet
A comprehensive cheat sheet for Stimulus.js, covering its core concepts, usage, and best practices to help you build maintainable JavaScript frontends.
Core Concepts
Controllers
Controllers are the fundamental building blocks of Stimulus applications. They connect behavior to your HTML.
|
Example:
|
Actions
Actions connect user events (e.g., clicks, form submissions) to controller methods.
|
Example:
This connects the |
Targets
Targets provide a way for controllers to reference specific elements within their element.
|
Example:
|
Values
Values allow you to associate typed data with your controller.
|
Example:
|
Advanced Usage
Lifecycle Callbacks
Stimulus provides lifecycle callbacks that are invoked at different points in a controller’s lifecycle.
|
Example:
|
Using `this.element`
|
Example:
|
Data Attributes
Stimulus relies heavily on |
Example:
|
Working with Forms
Submitting Forms
Stimulus can be used to enhance form submissions, handling them asynchronously with AJAX. |
Example:
|
Form Input Binding
Stimulus can be used to bind form inputs to controller values, allowing real-time updates and validation. |
Example:
|
Best Practices
Keep Controllers Small
Controllers should be focused on specific behaviors. Avoid creating large, monolithic controllers. |
If a controller becomes too complex, consider breaking it down into smaller, more manageable controllers. |
Use Targets Wisely
Targets are a powerful way to reference elements, but avoid overusing them. Only use targets when you need to directly manipulate an element from the controller. |
Consider using CSS classes and event delegation for simpler interactions. |
Leverage Values for Configuration
Use values to configure the behavior of your controllers. This allows you to customize controllers without modifying the code. |
Values also provide a way to type-check the data passed to your controllers. |