hotwired / stimulus

A modest JavaScript framework for the HTML you already have
https://stimulus.hotwired.dev/
MIT License
12.72k stars 424 forks source link

Clarify static elements with type Array need single quotes in html #796

Open mirandashort opened 3 weeks ago

mirandashort commented 3 weeks ago

It took me days to figure out why I wasn't able to get my static value to pass in as an array.

I have a function in toggle_controller.js

import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="toggle"
export default class extends Controller {

  static values = {
    elements: Array
  }

  toggle() {
    this.elementsValue.forEach(element => {
      console.log(`"${element}"`)
    });
  }
}

When written as the docs suggest for a string, I get the following:

  <button data-controller="toggle"
     data-toggle-elements-value="['one']"
     data-action="toggle#toggle">
     1
  </button>
controller.ts:20 Error invoking action "click->toggle#toggle"

SyntaxError: Unexpected token ''', "['one']" is not valid JSON

After so many tries, I switched the order of quotes to the following:

  <button data-controller="toggle"
     data-toggle-elements-value='["one"]'
     data-action="toggle#toggle">
     1
  </button>

When following the docs, I naturally went with double quotes first. I think it would be helpful to either clarify the importance of the syntax, or in general an example for each valid type (preferred).

marcoroth commented 3 weeks ago

Hey @mirandashort, thanks for opening this issue!

Sadly this is how the JSON.parse() function (which Stimulus uses under the hood) and how HTML escaping of attributes works.

But I agree, this is not ideal. Would you mind opening a pull request with your proposed changes so we can improve it for everyone? Thank you!