Justin Olson Justin Olson - 4 months ago 181
jQuery Question

onChange doesn't work with react and select2

I am using jquery select2 to make a selectbox. (Also new to react) I want to call a function when the data inside the multiple selectbox is changed. onClick and onBlur work as expected but onChange doesn't do anything. I think the issue has to do with how react renders it. If I add on the onChange effect after the component has rendered it works

$('#additional-filters-dropdown').attr('onChange', 'console.log("test")')
.onChange also works how I want in native html without react. And onChange works if the react element is an input field instead of select so I have no idea why they don't all play nice together.

React Component

var product_selections = React.createClass({
handleChange: function() {
console.log("Selction has been changed!");
},
render: function() {
return (
<div className='row'>
<br/>
<label htmlFor='product-dropdown'>
Product
<br/>
<select className='js-example-basic-multiple js-states form-control' id='product-dropdown' multiple='multiple' onChange={this.handleChange}>
</select>
</label>
</div>
);
}
});


Jquery Select2

$('#product-dropdown').select2({
data: [1,2,3,4]
});


app_main.js

var React = require('react');
var ReactDOM = require('react-dom');
ReactDOM.render(<ProductSelections/>, document.getElementById('product-selection-container'));


Anything that can point me in the right direction is helpful.

Answer

The onChange event is not triggered when the value is updated by javascript. In this case Select2.

When using jQuery with react you should try to keep the plugin set up contained inside the component.

Then you can try something like this using the react componentDidMount event:

var product_selections = React.createClass({
   handleChange: function() {
      console.log("Selction has been changed!");
   },

   componentDidMount: function(){
       $(this.refs['mySelect']).select2({
           change: this.handleChange
       });
   },

    render: function() {
        return (
            <div className='row'>
               <br/>
               <label htmlFor='product-dropdown'>
                  Product
                  <br/>
                  <select ref='mySelect' className='form-control' id='product-dropdown' multiple='multiple'>
                  </select>
               </label>
           </div>
        );
    }
});
Comments