Going Generic

Let's make our code more generic in this lesson.

Generic Stimulus Controllers

What do generic Stimulus controllers look like in our case?

What we have now is one controller that responds to a click by showing or hiding a target element and by changing the text of a target.

We can also think of this as two separate actions that respond to a click: one that adds and removes a CSS class and one that changes the text of a button. We’re going to split those into two separate controllers to show how Stimulus allows for the composition of small, generic pieces of action.

A clear downside is that this will complicate the code and the HTML. Let’s look at our code and discuss some upsides to this strategy.

Both of the generic Stimulus controllers are mostly subsets of our previous controller. Here’s the text one:

Get hands-on with 1200+ tech skills courses.