Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
mirandashort opened this issue Oct 16, 2024 · 1 comment
Open

Comments

@mirandashort
Copy link

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
Copy link
Member

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants