Stimulus JavaScript Framework

3.2.2 · active · verified Sun Apr 19

Stimulus is a modest, lightweight JavaScript framework designed by Basecamp to augment existing HTML with behavior, rather than taking over the entire front-end rendering. It operates on the principle of connecting JavaScript objects (controllers) to elements on the page using simple HTML data attributes (`data-controller`, `data-action`, `data-target`). It promotes a 'HTML-first' development approach, making it particularly popular in environments like Ruby on Rails with Hotwire (Turbo + Stimulus) where server-rendered HTML is prevalent. The current stable version is 3.2.2. Stimulus is actively maintained with regular updates and follows semantic versioning, introducing new features and occasional breaking changes between major versions. Its key differentiators include its small footprint, convention-over-configuration philosophy, and focus on enhancing server-rendered HTML rather than building single-page applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic 'Hello World' Stimulus application, showing how to connect a controller to HTML, define targets, and handle actions.

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Stimulus Hello World</title>
</head>
<body>
  <div data-controller="hello">
    <input data-hello-target="name" type="text" placeholder="Your name">
    <button data-action="click->hello#greet">Greet</button>
    <p data-hello-target="output"></p>
  </div>

  <script type="module">
    import { Application, Controller } from '@hotwired/stimulus';

    // Create a Stimulus application instance
    const application = Application.start();

    // Define and register the 'hello' controller
    class HelloController extends Controller {
      static targets = ['name', 'output'];

      connect() {
        console.log('Hello controller connected!');
        this.outputTarget.textContent = 'Enter your name and click greet!';
      }

      greet() {
        const name = this.nameTarget.value;
        this.outputTarget.textContent = `Hello, ${name || 'World'}!`;
      }
    }

    application.register('hello', HelloController);
  </script>
</body>
</html>

view raw JSON →