Using Values
Let's learn about Stimulus values in this lesson and see how they can be used to save the state of the controller.
We'll cover the following
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 attribute, and then -value
.
We want to start with one data HTML attribute for the visibility state of the element. This means our attribute name will be data-day-toggle-visible-value
. Note that, in this case, the attribute name is in dash-case in the HTML but will be in camelCase in the JavaScript.
We 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 we want them with the controller declaration so that the data references are easy to find.
That gives us:
Get hands-on with 1400+ tech skills courses.