📝 I’m loving Rails Stimulus; check out this example. #
I’m working on a site that has a left column for navigation. Standard stuff. But I wanted a simple control that lets you hide and show the left column.
When I first started using Stimulus, I would create a left_column_controller.js. Within it, in the connect() and disconnect() methods I would add and remove listeners. It worked, but it was verbose and I wasn’t enjoying Stimulus. Later, I refactored all my stimulus controllers to extract common interactions. Now I finally “get” Stimulus and I’m loving it!
I’m working on a site that has a left column for navigation. Standard stuff. But I wanted a simple control that lets you hide and show the left column.
When I first started using Stimulus, I would create a left_column_controller.js. Within it, in the connect() and disconnect() methods I would add and remove listeners. It worked, but it was verbose and I wasn’t enjoying Stimulus. Later, I refactored all my stimulus controllers to extract common interactions. Now I finally “get” Stimulus and I’m loving it!
Check out this example; it’s so simple and useful. When I want a special interaction on my page, I create a CSS class that I can add to the element in order to trigger the change I want. For example, adding “hide” collapses the left sidebar, adding “show” reveals additional fields on a form. Here is how I define this collapsible sidebar:
Below is a short video so you can see all the different interactions I get from it; you can see just how versatile this is.
Check out how versatile this is!
When I started thinking this way, it led me to extract multiple reusable controllers like this.
This part of my rails open-source ChatGPT app called HostedGPT. You can find the project on GitHub if you want to use it or help contribute to making it better!