Search⌘ K
AI Features

Using Values

Explore how to use Stimulus values to explicitly manage the state of your web components. Learn to declare, access, and manipulate boolean values to update button text and visibility dynamically, enhancing interactivity with minimal JavaScript.

Stimulus Values

Our code is simple so far, but it’s still missing a bit of functionality. Namely, we’ve not yet changed the text of the button from “Hide” to “Show.” On a structural level, we don’t have a place in the code that stores the state of the button. We have to infer the state from the presence or absence of the hidden class, but it’s better to have the state of the controller explicitly available.

We can do all of these things using another Stimulus concept: values. In Stimulus, values are a bit of syntactic sugar that allows us to use data attributes to store data that is specifically associated with a controller, and gives the controller some methods to manipulate that data directly without dealing with the DOM dataset itself.

Declaration

To declare a value, we use a similar pattern to what we’ve been using for targets. The attribute name itself has multiple parts: data-, the dash-case controller name followed by another hyphen (-), the name of the ...