Home > Article > Web Front-end > Enhance Your Rails pp with Stimulus.js and JavaScript Integration
Stimulus.js is a modest JavaScript framework that augments your HTML. It's the perfect companion for Rails' built-in functionality. In this post, we'll explore how to use Stimulus.js for JavaScript functionality, integrate it with other JavaScript libraries, and manage JavaScript dependencies effectively using Importmap.
Before we begin, ensure you have the following:
Rails 7 comes with default support for Stimulus.js. To get started, ensure Stimulus is included in your application by running:
rails new my_app cd my_app
You can find the Stimulus controllers in app/javascript/controllers.
Let's create a Stimulus controller to handle a simple click event. Run the following command:
rails generate stimulus hello
This will generate a new controller hello_controller.js in app/javascript/controllers. Open the file and add the following code:
// app/javascript/controllers/hello_controller.js import { Controller } from "@hotwired/stimulus" export default class extends Controller { static targets = ["output"] connect() { this.outputTarget.textContent = 'Hello, Stimulus!' } greet() { this.outputTarget.textContent = 'Hello, World!' } }
In your HTML, use the Stimulus controller:
<div data-controller="hello"> <h1 data-hello-target="output"></h1> <button data-action="click->hello#greet">Greet</button> </div>
When the button is clicked, the text will change to "Hello, World!".
Stimulus.js can work seamlessly with other JavaScript libraries. For example, let's integrate jQuery with Stimulus.js.
First, add jQuery using Importmap:
Add jQuery to your config/importmap.rb:
pin "jquery", to: "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
Then, import jQuery in your Stimulus controller:
// app/javascript/controllers/hello_controller.js import { Controller } from "@hotwired/stimulus" import $ from "jquery" export default class extends Controller { static targets = ["output"] connect() { this.outputTarget.textContent = 'Hello, Stimulus!' } greet() { $(this.outputTarget).fadeOut().fadeIn().text('Hello, jQuery!') } }
Managing JavaScript dependencies in Rails 7 is straightforward with Importmap. Here are some tips:
You can also add custom JavaScript files to your project. Place them in the app/javascript folder and import them where needed.
Stimulus.js provides a powerful yet simple way to add JavaScript functionality to your Rails application. By integrating it with other JavaScript libraries, you can create a rich and dynamic user experience. Properly managing your JavaScript dependencies ensures your application remains maintainable and up-to-date.
Happy coding!
The above is the detailed content of Enhance Your Rails pp with Stimulus.js and JavaScript Integration. For more information, please follow other related articles on the PHP Chinese website!