Picture of the author

GAURAV VARMA

← BACK TO BLOG

Stimulus 2.0 released – new Values & Classes API for controllers


Stimulus 2.0 brings new capabilities to your frontend controllers with the Values API and Classes API.

Values API

Define typed properties with default values:

1export default class extends Controller {
2  static values = { count: Number };
3
4  connect() {
5    console.log(this.countValue); // => 0 or passed value
6  }
7}

You can then set this value in your HTML:

1<div data-controller="my-controller" data-my-controller-count-value="5"></div>

Classes API

Bind CSS classes to behavior:

1static classes = ["highlight"]
2
3connect() {
4  this.element.classList.add(this.highlightClass) // returns class name
5}

You can specify the class name in your HTML:

1<div
2  data-controller="my-controller"
3  data-my-controller-highlight-class="active"
4></div>

Links

Summary

Stimulus 2.0 significantly enhances the power and flexibility of JavaScript controllers. The Values API simplifies the management of dynamic data and default configurations directly within the controller, while the Classes API provides a clean and declarative way to toggle and manage CSS classes based on controller state and actions. These additions allow for more expressive and maintainable frontend behavior without compromising Stimulus's core "modest" design principles.