Intro to Hotwire: HTML over the wire

Learn extra at:

In Stimulus, you utilize HTML attributes to attach components to “controllers,” that are chunks of JavaScript performance. For instance, if we wished to supply a clipboard copy button, we may do one thing like this:

<div data-controller="clipboard">
 
  <h1 data-clipboard-target="supply">
    Thimbleberry (Rubus parviflorus)
  </h1>
  <p>A fragile, native berry with massive, gentle leaves.</p>

  <button data-action="click->clipboard#copy">
    
    <span data-clipboard-target="suggestions">Copy Identify</span>
  </button>
</div>

Discover the data-contoller attribute. That hyperlinks the component to the clipboard controller. Stimulus makes use of a filename conference, and on this case, the file could be: clipboard_controller.js, with contents one thing like this:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {

  // Connects to data-clipboard-target="supply" 
  // and data-clipboard-target="suggestions"
  static targets = [ "source", "feedback" ]

  // Runs when data-action="click->clipboard#copy" is triggered
  copy() {
    // 1. Get textual content from the "supply" goal
    const textToCopy = this.sourceTarget.textContent
    
    // 2. Use the browser's clipboard API
    navigator.clipboard.writeText(textToCopy)

    // 3. Replace the "suggestions" goal to inform the consumer
    this.feedbackTarget.textContent = "Copied!"

    // 4. (Non-obligatory) Reset the button after 2 seconds
    setTimeout(() => {
      this.feedbackTarget.textContent = "Copy Identify"
    }, 2000)
  }
}

The static goal member offers these components to the controller to work with, based mostly on the data-clipboard-target attribute within the markup. The controller then makes use of easy JavaScript to carry out the clipboard copy and a timed message to the UI.

Leave a reply

Please enter your comment!
Please enter your name here