Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle special Bootstrap events in React?

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.

like image 714
FullStack Avatar asked Apr 18 '16 15:04

FullStack


1 Answers

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.

like image 120
respondcreate Avatar answered Nov 03 '22 09:11

respondcreate