developit / htm

Hyperscript Tagged Markup: JSX alternative using standard tagged templates, with compiler support.
Apache License 2.0
8.67k stars 170 forks source link

Variable as inline style not rendered #172

Closed codri closed 4 years ago

codri commented 4 years ago

Hi,

I'm trying to set a variable as an inline style in a div.

Neither this

      import {
        html,
        Component,
        render
      } from "https://unpkg.com/htm/preact/standalone.mjs";

      function App() {
        const [color, setColor] = useState("red");

        return html`
          <h1 style="color:${color}">app</h1>
        `;
      }

      render(
        html`
          <${App} />
        `,
        document.body
      );

Or this, is working:

    import {
        html,
        Component,
        render
      } from "https://unpkg.com/htm/preact/standalone.mjs";

      function App() {
        const [color, setColor] = useState("red");

        return html`
          <h1 style=${"color:" + color}">app</h1>
        `;
      }

      render(
        html`
          <${App} />
        `,
        document.body
      );

Is this an expected behaviour, or am I missing something?

jviide commented 4 years ago

The first example crashes with an error Uncaught ReferenceError: useState is not defined. This indicates that the problem is that useState has not been imported before it's used. Importing useState fixes the problem (at least in my environment 🙂):

      import {
        html,
        Component,
        render,
        useState // <--- added this
      } from "https://unpkg.com/htm/preact/standalone.mjs";

      function App() {
        const [color, setColor] = useState("red");

        return html`
          <h1 style="color:${color}">app</h1>
        `;
      }

      render(
        html`
          <${App} />
        `,
        document.body
      );

The second example can also be fixed by importing useState and removing an extraneous double quote after the style prop:

    import {
        html,
        Component,
        render,
        useState // <--- added this, and...
      } from "https://unpkg.com/htm/preact/standalone.mjs";

      function App() {
        const [color, setColor] = useState("red");

        return html`
          <h1 style=${"color:" + color}>app</h1>
        `; //                          ^--- ...removed a double quote here
      }

      render(
        html`
          <${App} />
        `,
        document.body
      );

I'll close this issue as it doesn't appear to be caused by a bug in HTM itself - if I'm mistaken then feel free to reopen the issue 👍