hono icon indicating copy to clipboard operation
hono copied to clipboard

Cannot pass onClick handler to jsx component

Open jannisbecker opened this issue 1 year ago • 1 comments

What version of Hono are you using?

4.6.3

What runtime/platform is your app running on?

Cloudflare Pages

What steps can reproduce the bug?

Repro here: https://github.com/jannisbecker/hono-repro

Essentially

  1. create a basic hono app
  2. write a JSX component function, add that component to a Hono route and add an onClick handler that e.g. logs to the console.
  3. run the app

What is the expected behavior?

When running the code and clicking on the element, it should execute the onClick event.

What do you see instead?

The click handler doesnt even appear in the DOM. In the repro given, I just see a div with no attributes. Needless to say, clicking it does nothing

Additional information

It's not like I want to "render" these components on the client. The route should convert the JSX down to raw html and send it to the client, as you'd expect from a server rendered app. However, I still need to attach client-side code to components, such as click listeners. I think they should just get passed to the html element inside the component and act as if I had written it directly in html.

Please correct me if this is intentional and I'm misunderstanding something.

jannisbecker avatar Sep 28 '24 16:09 jannisbecker

Hi @jannisbecker

This is expected behavior. Your application renders JSX only on the server side. To enable onClick, etc., a client-side JavaScript must be hydrated to the rendered HTML. To do this, you can create the mechanism yourself or use frameworks like HonoX. Or you can use hono/jsx only on the client side as an SPA. Example: https://github.com/yusukebe/hono-jsx-spa.

yusukebe avatar Oct 06 '24 08:10 yusukebe

This issue has been marked as stale due to inactivity.

github-actions[bot] avatar Nov 03 '24 00:11 github-actions[bot]

Closing this issue due to inactivity.

github-actions[bot] avatar Nov 06 '24 00:11 github-actions[bot]

TBH this doesn't really address the issue. onClick for a button is a valid HTML attribute. Take for example:

<button onClick="console.log('click');">Click here</script>

How does one do this in a hono/jsx template w/o client side rendering?

orbiteleven avatar Feb 03 '25 07:02 orbiteleven

FWIW this is the "workaround", but it's pretty poor:

<div
  dangerouslySetInnerHTML={{
     __html: `
      <button
        class="button is-primary"
        onClick="console.log('click')"
      >
        Submit
      </button>
    `,
  }}
></div>

orbiteleven avatar Feb 03 '25 07:02 orbiteleven

Please try to use <button onclick={...} /> Is this not working?

EdamAme-x avatar Feb 03 '25 13:02 EdamAme-x