Post

Ruby on Rails: How to Copy to Clipboard with Stimulus

A reusable Stimulus clipboard controller with configurable button feedback for Rails views.

Ruby on Rails: How to Copy to Clipboard with Stimulus

I needed a copy button on a Rails page and reached for Stimulus. Daniela Baron’s walkthrough explains targets, actions, values, and i18n step by step. It’s a great way to learn more about Stimulus.

Here are the steps more straightforward:

1
bin/rails generate stimulus clipboard

View

1
2
3
4
5
6
7
8
9
10
<div data-controller="clipboard"
  data-clipboard-confirm-value="Copied"
  data-clipboard-delay-ms-value="2000">
  <div data-clipboard-target="content">
    <%= @content_to_copy %>
  </div>
  <button data-action="clipboard#copy" data-clipboard-target="button">
    Copy
  </button>
</div>

Swap @content_to_copy for whatever text you want on the clipboard. Adjust data-clipboard-confirm-value and data-clipboard-delay-ms-value if you want different feedback.

Stimulus controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["content", "button"]

  static values = {
    confirm: { type: String, default: "Copied" },
    delayMs: { type: Number, default: 2000 }
  }

  copy() {
    const text = this.contentTarget.innerText

    navigator.clipboard.writeText(text)
      .then(() => {
        const originalText = this.buttonTarget.textContent
        this.buttonTarget.textContent = this.confirmValue

        setTimeout(() => {
          this.buttonTarget.textContent = originalText
        }, this.delayMsValue)
      })
      .catch((error) => {
        console.error("Failed to copy text to clipboard:", error)
      })
  }
}

Click the button, paste somewhere, and the label flips to “Copied” for two seconds. The Clipboard API needs a secure context (localhost or HTTPS).

This post is licensed under CC BY-NC 4.0 by the author.