Saturday, April 15, 2017

How to handle special Bootstrap events in React?

Leave a Comment

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.

1 Answers

Answers 1

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

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment