Member-only story

How to Pass Data from a Rails view to Stimulus: A Simple Guide

Phil Smy
4 min readJul 22, 2023

Everyone talks about the importance of pulling data from endpoints, but what if you already have your data on the page and want to pass it directly to your Stimulus controller? Here’s an efficient method of passing data to Stimulus!

The Problem

I have a page that has a bunch of modals on it that the user can open to see more details.

User can click ‘More…’ and get a modal

But we already have the details when we render the page. We just use some of them to produce this summary block. The rest are there, but unused.

In the modal, we want to present a Tabulator table. With Tabulator you have many options to get data into the view. Most people would say, fine, just load the data from an endpoint when the user opens a modal.

But I already have the data, why call the server again?

The Solution: Passing Data to Stimulus Directly

Here’s my Stimulus controller for my table

import { Controller } from "@hotwired/stimulus";

// Connects to data-controller="pc-period-details-table"
export default class…

--

--

Phil Smy
Phil Smy

Written by Phil Smy

Thinker, musician, writer and chief cook and code washer at ZonMaster.com. He’s also a published fiction author.

No responses yet