developit / htm

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

How to append dynamic value? like ``jsx`${value_from_var}``` #230

Closed ooling closed 1 year ago

ooling commented 1 year ago

Last night I wrote

let jsx = htm.bind(h);
let data = '<p>test</p>
let Test =()=> jsx`${data}`
render(Test(), document.querySelector('#content'));

But it just render plain text instead p element. How to solve that? Anyway I'm using ES Module right in the browser without NodeJS nor Bundle system.

rschristian commented 1 year ago

This will do the trick:

let jsx = htm.bind(h);
let data = '<p>test</p>';
let Test = () => jsx([data]);
render(jsx`<${Test} />`, document.querySelector('#content'));
ooling commented 1 year ago

@rschristian sure it worked, but it didn't work when I'm tried using functional component

rschristian commented 1 year ago

What do you mean? That is a function component.

ooling commented 1 year ago

@rschristian When using hooks I meant

rschristian commented 1 year ago

Okay, and how are you attempting to use hooks? It's a bit difficult to help you if I can't see what you're trying to do.

Edit: Here's an example of a component that uses your HTML string and has hook state. Hopefully this is what you're looking for?

ooling commented 1 year ago

can you just share the code here? it looks mesy : Screenshot_20221120-213009770

rschristian commented 1 year ago

it looks mesy :

That looks to be a rendering error in your browser, quite frankly. I'd use something else. It's like elements are duplicated out of place and without styling. Really odd.

can you just share the code here?

import { html, render, useState } from 'https://cdn.skypack.dev/htm/preact/standalone';

const data = '<h1 style="color: white">Hello World!</h1>';

function App() {
    const [score, setScore] = useState(0);
    const Button = () => html`<button onClick=${() => setScore(score + 1)}>${score}</button>`;

    return html`
      ${html([data])}
      <${Button} />
    `;
}

render(html`<${App} />`, document.body);
ooling commented 1 year ago

It worked, noice!