StimulusReflex is a newer gem designed to make Rails more responsive. It's similar to Phoenix's LiveView. They both use web sockets to pipe communications between the browser and the server, and this can make web pages responsive.
viewcomponentreflex takes StimulusReflex a step further in that it allows us to manipulate view_components instead of complete Rails views. View components are nice in that they allow us to break up a view into reusable components that can be unit tested separately from views.
Our goal is to set this up in a new project and get something working. If you're following along your first step is to install ruby and rails however you want, and then
rails new a project. It should be noted that these gems are in active development, so you may run into issues from changes.
bundle exec rails webpacker:install:stimulus
Next comes adding in the StimulusReflex gem.
bundle add stimulus_reflex
yarn add stimulus_reflex
bundle exec rails stimulus_reflex:install
NOTE: As of 2020-08-08 this worked with version 2.1.2. Version 2.1.3 appears to not work with these instructions. You can pin the viewcomponentreflex to 2.1.2 in your Gemfile..
This part is easy. We just need to add the gem for viewcomponentreflex
bundle add view_component_reflex
Also easy, add the following to config/application.rb right after require 'rails/all'
At this point if you run
bundle exec rails server and then visit http://localhost:3000/ you should see the default "Yay! You’re on Rails!" page.
First we need a Rails controller and view to make this work. So the first step is getting the StateExample controller up with a Rails generator.
bundle exec rails generate controller StateExample how_neat
At this point you should be able to access http://localhost:3000/stateexample/howneat if you left your rails server running.
Then to render that new component we add
<%= render(CounterComponent.new) %> to
app/views/state_example/how_neat.html.erb. You can put it anywhere.
At this point you should see the new component in the view we just created. If not try restarting your rails server.
https://github.com/danclark5/stimulus_expo in case you want to just get to the end result.Back