htmx icon indicating copy to clipboard operation
htmx copied to clipboard

HTMX not detecting elements loaded in via React

Open danthegoodman1 opened this issue 1 year ago • 1 comments

I am using Vite + Typescript + React and have htmx imported the following way:

vite.config.ts

export default defineConfig({
  plugins: [
    react(),
    inject({
      htmx: "htmx.org",
    }),
  ],

With a component like:

<div hx-target="this" hx-swap="outerHTML">
        <div>
          <label>First Name</label>: Joe
        </div>
        <div>
          <label>Last Name</label>: Blow
        </div>
        <div>
          <label>Email</label>: [email protected]
        </div>
        <button hx-get="/contact/1/edit" className="btn btn-primary">
          Click To Edit
        </button>
      </div>

all I see in debug logs are: image

when clicked, nothing happens

and htmx does not behave as expected on the component.

If i place that exact html inside the index.html, it behaves as expected and htmx hooks in:

image

when clicked, the content is swapped as expected.

This is an otherwise vanilla npm create vite@latest with typescript, react, and tailwind installed

danthegoodman1 avatar Feb 10 '24 00:02 danthegoodman1

I've also tried downloading an importing, and using import 'htmlx.org', same behavior observed

danthegoodman1 avatar Feb 10 '24 00:02 danthegoodman1

You need to call htmx.process() when a new DOM element has been created via Javascript:

https://htmx.org/docs/#3rd-party

In this case you would need to pass the actual DOM element to the process function whenever the component is mounted

danielnieto avatar Feb 10 '24 06:02 danielnieto

That fixed it, thanks!

danthegoodman1 avatar Feb 10 '24 13:02 danthegoodman1