How to use Select2 with Reactjs? How to use Select2 with Reactjs? reactjs reactjs

How to use Select2 with Reactjs?


We are using this wrapper, but there are too many problems around it.

First of all, you can't test code where it is used in NodeJS, because of this issue.Secondly we had problems with initialization of various select2 components via defaultValue parameter. Only one (randomly) of these elements was initalized.

Therefore we going to dump it and replace with react-select soon.

EDIT: We replaced react-select2-wrapper with react-select. It works great for us.


If you're using refs [docs], you can access the node via its refs attribute in the componentDidMount function and pass that to select2() :

var Select = React.createClass({  handleChange: function () {    this.prop.onChange(      this.refs.myRef.value    );  },  componentDidMount: function () {    // Call select2 on your node    var self = this;    var node = this.refs.myRef; // or this.refs['myRef']    $(node)      .select2({...})      .on('change', function() {        // this ensures the change via select2 triggers         // the state change for your component         self.handleChange();      });  },  render: function () {    return (      <select         ref="myRef"        onChange={this.handleChange}>        // {options}      </select>    );  }});

I don't believe this is the "React way," but this may help if you don't want to use react-select or some other tool.


Since you're using React, you'd be better off looking for React components rather than jQuery plugins. You can use for eaxmple react-select, which is pretty similar to Select2.