How to use Select2 with Reactjs?

user3673959 picture user3673959 · Feb 3, 2016 · Viewed 30.1k times · Source

I have dependent fields like this

    <List>
     <select>
      <option></option>
      <option></option>
     </select>
     <select>
      <option></option>
      <option></option>
     </select>
     <input />
   </List>

If I had 5 <List/> components.How do I add Select2 to each component.I googled online.But couldn't find any working solution.

Code below for react-select.Getting error TypeError: event.target is undefined.

var React = require('react');
var ReactDOM = require('react-dom');
var Select = require('react-select');

var Page = React.createClass({

    getInitialState: function () {
        return {
            firstValue: ''
        }
    },

    handleFirstLevelChange : function (event) {
        this.setState({
            firstValue: event.target.value
        });
    },
    render : function(){

        var options = [
            { value: '', label: 'Select an option' },
            { value: 'one', label: 'One' },
            { value: 'two', label: 'Two' }
        ];

        return (<Select
            value={this.state.firstValue}
            options={options}
            onChange={this.handleFirstLevelChange}
            />)
    }
});

ReactDOM.render(<Page />, document.getElementById('root'));

Answer

luboskrnac picture luboskrnac · Feb 3, 2016

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.