Published 01/11/2020
Last Updated 20/11/2024

I've started a new Rails 6 app and want to try out Stimulus.js instead of a more complex JS library such as VueJs or ReactJs. Stimulus.js is created by Basecamp, creator of Rails so it is supposed to easily integrated with Rails as I would like to use Rails helper functions in views instead of writing manual forms in VueJs with extra API endpoints for it.

As it states on the homepage

A modest JavaScript framework for the HTML you already have.

Stimulus.js doesn't seek to replace good-old-HTML template like Vue/React. Instead it blends itself into existing HTML code and connect it to controllers - the enities that hold JS interactive code & functions.

There is a simple example on Stimulus.js home page but here I want to demonstrate a little more complicated example.

The problem

I have a form with three fields: gross_amountdeduction_amount and net_amount

The logic as follow

https://ngaunhien.net/uploads/image/323/image-1604220835173.png

Step-by-step solution

Setup Stimulus.js

Add Stimulus npm package

yarn add stimulus

Add Stimulus config to app/javascripts/packs/application.js

import { Application } from 'stimulus'
import { definitionsFromContext } from 'stimulus/webpack-helpers'

const application = Application.start()
// controllers will be in app/javascripts/controllers
const context = require.context('../controllers', true, /\\\\.js$/)
application.load(definitionsFromContext(context))