Popper, Rails and Stimulus

How to implement Popper in a Rails 7 app using Stimulus

Stéphane Paquet
3 min readJan 18, 2022
Photo by Jackson So on Unsplash

What is Popper?

Popper is a javascript positioning engine that facilitates the development of tooltips and popovers. It’s a very minimal engine as the lite version only adds between 3 and 4kB (depending on the version and your compression algorithm).

More about popper can be found here

Let’s create a Rails 7 project

We will create a basic Rails 7 project using the default SQLite database as we are just going to focus on a very trivial popper.js setup.

rails new popper_project --css=tailwind --javascript=esbuild

Once in the project let’s run yarn add @popperjs/core to add the popper engine to the project.

At this point you might also want to create a Rails controller to host our button.

rails g controller welcome index

and change the routes.rb to make the previous page the default one for the project.

root "welcome#index"

The Stimulus Controller

Now let’s create the stimulus controller that we are going to use to handle popper: rails g stimulus popper

This creates popper_controller.js in app/javascript/controllers.

Edit the controller so that its content looks like the following:

popper_controller.js

This controller defines:

  • 2 targets that we are going to use to connect the elements that trigger the popover and its content.
  • 2 values that are optional. They are used to configure different display from the frontend.
  • The show and hide methods that are used to display and remove the popover when the mouse is over (or leave) the element. We will later see that the event listener are not defined in the stimulus controller. Defining event listener inside the stimulus controller should be limited as this is raising a lot of issues as explained in this article of Better Stimulus
  • The connect method that is used to connect the element to the stimulus controller and its matching destroy method used to remove the controller from the element when the element is removed from the screen.

Let’s add a few more files to style popper.js

popper.css

In this example we are taking the CSS from the popper.js documentation. The popper.css file is placed next to the application.tailwind.css file in the app/assets/stylesheets folder.

Edit application.tailwind.css

In order to load the popper style we just defined above we need to load the popper.css file.

Open the application.tailwind.css file and add at the top:

@import "popper.css";

Create the Frontend

Create the index.html.erb file in app/views/welcome and add the following lines:

Voilà!

Nota:

Yes this example does not really requires tailwind to be used, but real life projects are more complex and use tailwind css.

--

--