Using Values

Let's learn about Stimulus values in this lesson.

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 attributes to the same DOM element that declares the controller, though technically they can be attached to any DOM element inside the controller. Most of the time you want them with the controller declaration so that the data map references are easy to find, which gives us:

Get hands-on with 1400+ tech skills courses.