13

In straight up jQuery, I can do something like

$('#myCollapsible').on('click', 'hidden.bs.collapse', function () {
  // do something…
})

but is there a "right" way to do it in React? If the above is the way to go, where should I place that event handler? Please note that I am not using the react-bootstrap plugin.

3 Answers 3

23
+50

The right way to handle events not directly supported by React is by adding an event listener to the DOM node after the component mounts, and removing it when the component unmounts:

class MyCollapsible extends React.Component {
  constructor() {
    super()
    // Bind the method in the constructor instead of binding it in render, so you only do it once
    this.handleHiddenBsCollapse = this.handleHiddenBsCollapse.bind(this)
  }

  componentDidMount() {
    this.myCollapsible.addEventListener('hidden.bs.collapse', this.handleHiddenBsCollapse)
  }

  componentWillUnmount() {
    this.myCollapsible.removeEventListener('hidden.bs.collapse', this.handleHiddenBsCollapse)
  }

  handleHiddenBsCollapse(event) {
    // Do something...
  }

  render() {
    // Settings refs with node => this.bla = node is recommended
    // because this.refs is deprecated.
    // in this example "node" is the DOM node itself, not a react reference
    return (
      <div ref={node => (this.myCollapsible = node)} />
    )
  }
}

Documentation for using DOM refs: https://facebook.github.io/react/docs/refs-and-the-dom.html

4
  • 1
    Weird. I'm not getting the events. When I look at the node in Chrome tools, the handlers are there. The handlers I added with jQuery $('.panel').on("hidden.bs.collapse", tc); show up as being on hide and show and they trigger. Apr 11, 2017 at 1:46
  • Check to see that your bindings are correct in the react version. Also try (foo, bar) => this.handleHiddenBsCollapse(foo, bar) as the event handler in addEventListener to see what exactly you're getting.
    – fnune
    Apr 11, 2017 at 8:39
  • 2
    I think the problem is that jQuery events are "namespaced" in a way that doesn't work with addEventListeners. Apr 12, 2017 at 0:19
  • @FaustoNA I am trying to do something similar with functional component. I am able to trigger event on dropdown close but I also want to access selected element. My problem is that inside triggered function selected items array is always empty.
    – Anil
    Oct 19, 2020 at 7:48
3

I know I'm more than two years late to answer this question but I ran into this same problem recently and Fausto NA's answer didn't work for me. I was able to successfully attach my event listeners by leveraging the affected component's componentDidMount method:

import $ from 'jquery';
import React from 'react';

class App extends React.Component {

    componentDidMount() {
        $('#myCollapsible').on('click', 'hidden.bs.collapse', function () {
            alert('#myCollapsible -- hidden.bs.collapse');
        })
    }

    render() {
        return (
            // This is the render method where `#myCollapsible` would be added to the DOM. 
        )
    }
}

Why this works: if you try attaching an event handler to an element that isn't currently in the DOM then jQuery won't be able to successfully attach an event to it. In the example above, the jQuery code within the componentDidMount method doesn't run until #myCollapsible is in the DOM. This ensures jQuery can find it and properly attach your event handler.

0

If you're building functional component, you should use useEffect hook.

Also maybe you'll need to use window.$("#myCollapsible") instead of $("#myCollapsible")

import React, { useEffect } from 'react'
import $ from 'jquery'

export default function MyComponent() {
    useEffect(() => {
        // This code runs when component is mounted:
        window.$("#myCollapsible").on('hidden.bs.collapse', function (e) {
            console.log('hidden.bs.collapse');
        });
        return () => { // This code runs when component is unmounted
            window.$("#myCollapsible").off('hidden.bs.collapse');
        }
    }, []);

    // ...
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.