Top Related Projects
A rugged, minimal framework for composing JavaScript behavior in your markup.
A full-stack framework for Laravel that takes the pain out of building dynamic UIs.
⚛️ Fast 3kB React alternative with the same modern API. Components & Virtual DOM.
Cybernetically enhanced web apps
A declarative, HTML-based language that makes building web apps fun
Quick Overview
Stimulus is a modest JavaScript framework designed to enhance HTML by connecting DOM elements to JavaScript objects automatically. It aims to simplify the process of adding dynamic, interactive behaviors to web applications while promoting a clean separation of concerns.
Pros
- Lightweight and easy to learn, with a minimal API
- Seamlessly integrates with existing HTML and server-rendered pages
- Encourages writing less JavaScript by leveraging HTML data attributes
- Works well with other frameworks and libraries
Cons
- Limited in scope compared to full-featured frameworks like React or Vue
- May require more HTML markup for complex interactions
- Not ideal for building highly dynamic, single-page applications
- Smaller community and ecosystem compared to more popular frameworks
Code Examples
- Basic controller setup:
// hello_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = [ "name", "output" ]
greet() {
this.outputTarget.textContent = `Hello, ${this.nameTarget.value}!`
}
}
- Handling form submission:
// form_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = [ "form", "status" ]
submit(event) {
event.preventDefault()
fetch(this.formTarget.action, {
method: this.formTarget.method,
body: new FormData(this.formTarget)
})
.then(response => response.json())
.then(data => {
this.statusTarget.textContent = "Form submitted successfully!"
})
}
}
- Managing a toggle state:
// toggle_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static classes = [ "active" ]
toggle() {
this.element.classList.toggle(this.activeClass)
}
}
Getting Started
-
Install Stimulus:
npm install @hotwired/stimulus
-
Set up your application:
// application.js import { Application } from "@hotwired/stimulus" import HelloController from "./controllers/hello_controller" const application = Application.start() application.register("hello", HelloController)
-
Use in HTML:
<div data-controller="hello"> <input data-hello-target="name" type="text"> <button data-action="click->hello#greet">Greet</button> <span data-hello-target="output"></span> </div>
Competitor Comparisons
A rugged, minimal framework for composing JavaScript behavior in your markup.
Pros of Alpine
- Lightweight and minimal, with a smaller learning curve
- More flexible and less opinionated, allowing for quicker prototyping
- Can be used without a build step, making it easier to integrate into existing projects
Cons of Alpine
- Less structured approach may lead to less maintainable code in larger applications
- Lacks some of the more advanced features and conventions found in Stimulus
- Smaller ecosystem and community compared to Stimulus
Code Comparison
Alpine:
<div x-data="{ open: false }">
<button @click="open = !open">Toggle</button>
<span x-show="open">Content</span>
</div>
Stimulus:
<div data-controller="toggle">
<button data-action="click->toggle#toggle">Toggle</button>
<span data-toggle-target="content" class="hidden">Content</span>
</div>
// toggle_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "content" ]
toggle() {
this.contentTarget.classList.toggle("hidden")
}
}
Both frameworks aim to enhance HTML with JavaScript functionality, but Alpine uses a more declarative approach directly in the HTML, while Stimulus separates concerns with dedicated controller files.
A full-stack framework for Laravel that takes the pain out of building dynamic UIs.
Pros of Livewire
- Full-stack framework with server-side rendering, reducing JavaScript complexity
- Seamless integration with Laravel, leveraging existing PHP skills
- Real-time updates without writing custom JavaScript
Cons of Livewire
- Tighter coupling to the backend, potentially limiting flexibility
- Higher server load due to more frequent requests
- Steeper learning curve for developers new to the Laravel ecosystem
Code Comparison
Stimulus:
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "name" ]
greet() {
console.log(`Hello, ${this.nameTarget.value}!`)
}
}
Livewire:
class HelloWorld extends Component
{
public $name = '';
public function render()
{
return view('livewire.hello-world');
}
}
Summary
Stimulus is a lightweight JavaScript framework that enhances existing HTML, while Livewire is a full-stack framework for Laravel that allows building dynamic interfaces with minimal JavaScript. Stimulus offers more flexibility and is framework-agnostic, whereas Livewire provides a more integrated experience within the Laravel ecosystem. The choice between the two depends on the project requirements, team expertise, and desired level of backend integration.
⚛️ Fast 3kB React alternative with the same modern API. Components & Virtual DOM.
Pros of Preact
- Smaller bundle size and faster performance
- Full React-compatible API, allowing easy migration from React
- Virtual DOM for efficient updates and rendering
Cons of Preact
- Smaller ecosystem compared to React
- Less suitable for large, complex applications
- Limited built-in features, requiring additional libraries for advanced functionality
Code Comparison
Stimulus:
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "name" ]
greet() {
console.log(`Hello, ${this.nameTarget.value}!`)
}
}
Preact:
import { h, Component } from 'preact'
class Greeting extends Component {
render({ name }) {
return <div>Hello, {name}!</div>
}
}
Summary
Stimulus is a lightweight JavaScript framework for adding behavior to HTML, focusing on enhancing existing markup. It's ideal for server-rendered applications and progressive enhancement.
Preact, on the other hand, is a fast, 3kB alternative to React with the same modern API. It's better suited for building complex, interactive user interfaces and single-page applications.
Choose Stimulus for simpler DOM interactions and server-rendered apps, while Preact is preferable for React-like development with a smaller footprint.
Cybernetically enhanced web apps
Pros of Svelte
- Compiles to vanilla JavaScript, resulting in smaller bundle sizes and better performance
- Offers a more intuitive and less boilerplate-heavy syntax
- Provides built-in state management and reactivity
Cons of Svelte
- Smaller ecosystem and community compared to more established frameworks
- Limited server-side rendering options
- Steeper learning curve for developers accustomed to traditional frameworks
Code Comparison
Svelte component:
<script>
let count = 0;
function increment() {
count += 1;
}
</script>
<button on:click={increment}>
Clicks: {count}
</button>
Stimulus controller:
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = [ "output" ]
count = 0
increment() {
this.count++
this.outputTarget.textContent = `Clicks: ${this.count}`
}
}
Svelte offers a more concise and declarative approach, while Stimulus follows a more traditional object-oriented pattern. Svelte's reactivity is built-in, whereas Stimulus requires manual DOM updates.
A declarative, HTML-based language that makes building web apps fun
Pros of Marko
- Offers server-side rendering out of the box, enhancing performance and SEO
- Provides a more comprehensive framework for building full web applications
- Supports both single-file components and separate files for markup and logic
Cons of Marko
- Steeper learning curve due to its unique syntax and concepts
- Less flexibility for integrating with existing JavaScript codebases
- Smaller community and ecosystem compared to more mainstream frameworks
Code Comparison
Marko component:
class {
onCreate() {
this.state = { count: 0 };
}
increment() {
this.state.count++;
}
}
<button on-click('increment')>
Count: ${state.count}
</button>
Stimulus controller:
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "output" ]
count = 0
increment() {
this.count++
this.outputTarget.textContent = this.count
}
}
Marko offers a more concise syntax for defining components with integrated markup and logic, while Stimulus separates concerns between HTML and JavaScript, requiring more explicit connections between the two.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Stimulus
A modest JavaScript framework for the HTML you already have
Stimulus is a JavaScript framework with modest ambitions. It doesn't seek to take over your entire front-endâin fact, it's not concerned with rendering HTML at all. Instead, it's designed to augment your HTML with just enough behavior to make it shine. Stimulus pairs beautifully with Turbo to provide a complete solution for fast, compelling applications with a minimal amount of effort.
How does it work? Sprinkle your HTML with controller, target, and action attributes:
<div data-controller="hello">
<input data-hello-target="name" type="text">
<button data-action="click->hello#greet">Greet</button>
<span data-hello-target="output"></span>
</div>
Then write a compatible controller. Stimulus brings it to life automatically:
// hello_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = [ "name", "output" ]
greet() {
this.outputTarget.textContent =
`Hello, ${this.nameTarget.value}!`
}
}
Stimulus continuously watches the page, kicking in as soon as attributes appear or disappear. It works with any update to the DOM, regardless of whether it comes from a full page load, a Turbo page change, or an Ajax request. Stimulus manages the whole lifecycle.
You can write your first controller in five minutes by following along in the Stimulus Handbook.
You can read more about why we created this new framework in The Origin of Stimulus.
Installing Stimulus
You can use Stimulus with any asset packaging systems. And if you prefer no build step at all, just drop a <script>
tag on the page and get right down to business.
See the Installation Guide for detailed instructions.
Getting Help
Looking for the docs? Once you've read through the Handbook, consult the Stimulus Reference for API details.
Have a question about Stimulus? Connect with other Stimulus developers on the Hotwire Discourse community forum.
Contributing Back
Find a bug? Head over to our issue tracker and we'll do our best to help. We love pull requests, too!
We expect all Stimulus contributors to abide by the terms of our Code of Conduct.
Development
- Fork the project locally
yarn install
yarn start
- to run the local dev server with examplesyarn test
- to run the unit testsyarn lint
- to run the linter with ESLintyarn format
- to format changes with Prettier
Acknowledgments
Stimulus is MIT-licensed open-source software from Basecamp, the creators of Ruby on Rails.
Continuous integration VMs generously provided by Sauce Labs.
© 2024 Basecamp, LLC.
Top Related Projects
A rugged, minimal framework for composing JavaScript behavior in your markup.
A full-stack framework for Laravel that takes the pain out of building dynamic UIs.
⚛️ Fast 3kB React alternative with the same modern API. Components & Virtual DOM.
Cybernetically enhanced web apps
A declarative, HTML-based language that makes building web apps fun
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot