Search code examples
javascriptruby-on-railsvalidationrefactoringstimulusjs

Javascript code refactor to use in Stimulus controller


How to refactor JS code like this:

const fileInput = document.getElementById('input');
const p = document.querySelector('p');
fileInput.onchange = () => {
  const selectedFiles = [...fileInput.files];
  p.textContent = selectedFiles.map(s => s.size).join(', ');
}

to make it work in rail's Stimulus? I have very little experience with JS and want to have one or two examples of implementing JS code in Stimulus controllers, so I have material to refactor other cases on my own. Much thanks.


Solution

  • One possible solution:

    <div data-controller="file">
      <input type="file" data-file-target="input" data-action="change->file#displayText" id="my-input">
      <output data-file-target="text" for="my-input"></output>
    </div>
    
    // filename_controller.js
    
    // Connects to data-controller="file"
    export default class extends Controller {
      static targets = ["input", "text"]
      
      displayText() {
        const selectedFiles = [...thisInputTarget.files];
        this.textTarget.textContent = selectedFiles.map(s => s.size).join(', ');
      }
    }