Search⌘ K

Using Values

Explore how to declare and use Stimulus values to explicitly store and manipulate button states and text in a Rails application. Understand the integration of data attributes, value types, and controller methods to manage UI changes effectively and maintain synchronization between data and DOM elements.

We'll cover the following...

Our code is pretty simple so far, but it’s still missing a bit of functionality. We’re not yet changing the text of the button from “Hide” to “Show.” On a more structural level, we don’t have a place in the code that explicitly stores the state of the button. We have to infer the state from the presence or absence of the is-hidden class, which is not a terrible thing to do, but more explicitness is probably useful.

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 the 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 dataset itself.

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

We want to start with one data HTML attribute for the state of the toggle. This means our attribute name will be data-day-toggle-visible. Note that in this case, the attribute name is in dash-case in the HTML but will be camelCase in the JavaScript.

You typically add the value ...