- Create a new Stimulus controller file, either:
- with
rails g stimulus my_feature
, or - by manually adding a file in the
controllers
directory of your Rails application, e.g.,app/javascript/controllers/my_feature_controller.js
.
- The controller file should define your Stimulus controller class:
// app/javascript/controllers/my_feature_controller.js
import { Controller } from "stimulus";
export default class extends Controller {
connect() {
// The connect action gets run as soon as an element connected to your controller is initialized
console.log("MyFeatureController connected!");
}
}
- In your HTML view, use the
data-controller
attribute to connect the controller to an element. The syntax isdata-controller=<name-of-your-controller>
:
<div data-controller="my-feature">
<!-- Your content here -->
</div>
- In your controller, define a new method that will be triggered by an event (e.g.
doSomething
):
// app/javascript/controllers/my_feature_controller.js
// ...
export default class extends Controller {
// ...
doSomething() {
console.log("Button clicked!");
}
}
- In your HTML view, use the
data-action
attribute to associate the action with an event. The syntax isdata-action="<event>-><name-of-your-controller>#<nameOfTheAction>"
:
<div data-controller="my-feature">
<button data-action="event->my-feature#doSomething">Click me</button>
</div>
Here is the list of all the JavaScript events you can use.
- In your controller, use the
targets
property to define named references to HTML elements. You can then access those elements usingthis.<targetName>Target
:
// app/javascript/controllers/my_feature_controller.js
// ...
export default class extends Controller {
static targets = ["output"];
// ...
doSomething() {
console.log(this.outputTarget);
this.outputTarget.innerText = "Hello, Stimulus!";
}
}
- In your HTML view, use the
data-target
attribute to indicate where the element should be referenced. The syntax isdata-<name-of-your-controller>-target="<target-name>
:
<div data-controller="my-feature">
<p data-my-feature-target="output"></p>
</div>
- In your controller, use the
values
property to define named references to dynamic values, and specify their datatype. They become accessible in your controller usingthis.<valueName>Value
:
// app/javascript/controllers/my_feature_controller.js
// ...
export default class extends Controller {
static values = { greeting: String };
// ...
initialize() {
console.log("Initialized with greeting:", this.greetingValue);
}
}
- In your HTML view, use the
data-value
attribute to set the dynamic value on the same element your controller is connected to. The syntax isdata-<name-of-your-controller>-<name-of-the-value>-value="The value you want inside"
:
<div data-controller="my-feature" data-my-feature-greeting-value="Hello from data-value!">
<!-- Content here -->
</div>