phenixdigital / phoenix_storybook

A pluggable storybook for your Phoenix components.
MIT License
708 stars 54 forks source link

Modal component using `.showModal()` does not work due to variation_id not being a valid javascript variable #495

Closed noozo closed 2 months ago

noozo commented 3 months ago

I have a modal component with an optional CTA button to open it via JS, using the dialog element method (with onclick):

<button
        :if={slot_assigned?(assigns, :cta)}
        type="button"
        onclick={"#{@id}.showModal();"}
        class={@cta_button_class}
      >

The problem is that the generated id will not be a valid JS variable name, and the showModal function will fail when i click the CTA button in a story:

image

This is the generated id, shown when clicking the error in the JS console:

modal-single-cta.showModal();
noozo commented 3 months ago

Got around it by explicitly defining the variation id in the template of the variation:

%Variation{
        id: :cta,
        attributes: %{},
        slots: [
          """
           This is my modal text
           <:cta>Click this CTA</:cta>
          """
        ],
        template: """
          <.psb-variation id="cta_modal" />
        """
      },
cblavier commented 2 months ago

this is the way to go 👍 remember that you can also get the variation_id injected into your template by referencing :variation_id anywhere in your template markup