Reagent Adding Event Listener to a Component

Hi all! I am currently debugging a Reagent Form-3 Component. The essence of the problem is that I need to add an event listener to the component, but it’s not quite clear how to refer to the HTML component itself when doing this. As an example:

(defn Component

     (fn [this]
       (let [event-handler (fn [e] ())])
           (.addEventListener this "click" event-handler true))}))

This does not work, as it throws the error

TypeError: this$.addEventListener is not a function

I cannot seem to find a way to refer to the “this” of a component when adding the event. Additionally, this is part of a much larger component, with pretty complex behavior, so hopefully there’s a way of doing this with minimal friction with regards to the example above, but I’m open to any suggestions or advice.

There is the this-as macro

1 Like

It seems that :component-did-mount does not return a DOM node. You need to call (reagent/dom-node comp) on the component it returns to get the DOM node.

But why are you even adding the click handler imperatively in a callback? That is usually not the way to do it in reagent (or React for that matter). Instead, do it declaratively as part of the attribute map in the render function by setting the :on-click key to your on-click handler. It’s less code, much more idiomatic, clearer, and less prone to weird bugs.


Thank you for the replies! These seem to be working out great!

@simongray, I agree, this isn’t very idiomatic or clean. However, the original code that I’m trying to fix does not attempt to add an eventlistener, but instead modifies (removes, changes) event listeners that are already attached to the element(s) in various ways, I simply just used addEventListener as a simple example. It would however definitely be a good idea to look into incorporating these into idiomatic React code, for me and for anyone else that stumbles across this forum.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.