Stimulus Use Cases

Viktor Markov
3 min readApr 18, 2022

--

I’m finishing my first project with Stimulus and I’ve decided to create a document with examples of how we can implement different features with that framework.

I’ll cover:

  • Confirmation alert
  • Image upload preview
  • Textarea auto height
  • Form validation

If you are not familiar with Stimulus yet — it’s a simple framework that allows to write structured JavaScript code within controllers. Stimulus has good documentation on the official website.

Confirmation alert

The goal is to inform users that they are about to leave our website.

We have data-action attribute which allows to interact with click events through showConfirmation function of Confirmation controller.

Source code on CodePen and GitHub.

Image upload preview

We have input for image uploads and now we need to create preview of an uploaded picture and possibility to clear it.

When user selects an image, stimulus executes updatePreview function. It checks if there are any files were uploaded and then shows or hides the preview.

When a user clicks on the clear upload button, clearUpload function is called. It nullifies the value of the upload input and triggers updatePreview.

Source code on CodePen and GitHub.

Textarea auto height

Textarea cannot increase its size to fit a whole text. Usually we want to implement this feature.

Source code on CodePen and GitHub.

Form validation

There are a lot of validation methods. Here is one of them:

We group inputs by validation conditions. Name and surname must be filled with at least one symbol. Age must be equal or greater than 18.

Source code on CodePen and GitHub.

Thank you for your attention!

The full version of the examples is here. Feel free to correct the code and advise new use cases based on your experience 🙂

--

--