2

I am having problems with select tag implementation in React.js. Here is what I have:

var ProfessorsFilter = React.createClass({
  getInitialState: function(){
    return(
    {
      visibleDepartments: [],
      selectedSchoolId: 1
    }
    )
  },
  selectSchool: function(event){
    console.log("select school");
    alert("select ");
    this.setState({selectedSchoolId: event.target.value});
  },
   render: function () {
     var schoolOptions = this.props.schools.map(function(school, index){
       return (
           <option key={index} value={school.id}>{school.name}</option>
       );
     });
       return(

                 <select onChange={this.selectSchool} value={this.state.selectedSchoolId} className="select-2">
                   {schoolOptions}
                 </select>

       )
   }
});

So, I am doing controlled component. But onchange does not fire my method selectSchool. EDIT: jsfiddle: https://jsfiddle.net/wc02bvaj/ BTW. I am also using select2.

EDIT2: It turned out to be problem with select2.

6
  • Can you create a fiddle or equivalent? There's nothing obviously wrong. Are there any errors in the console? Commented Aug 21, 2016 at 13:10
  • @DaveNewton, no, no errors Commented Aug 21, 2016 at 13:11
  • are you using any jquery plugin like select2? Commented Aug 21, 2016 at 13:20
  • @Vijay, btw, yes, I am using select2. Commented Aug 21, 2016 at 13:38
  • It probably takes the onChange event for itself. You can confirm by removing it from the select and verifying the onChange in React works. Commented Aug 21, 2016 at 13:50

1 Answer 1

2

If you're using jQuery along with React on the same DOM elements it will generally cause problems. Either leave that unmanaged by React, use a React equivalent and remove jQuery, or in this case, you have a few options.

The easiest options is to just use https://github.com/rkit/react-select2-wrapper.

Alternatively you could roll your own solution, e.g., Select2 has an change callback on its own. If you're using Redux (it doesn't look like you are) you could change the state by dispatching an action from the Select2 change handler. You might be able to listen to the jQuery Select2 change event by registering a handler in your ProfessorsFilter and setting the state there.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.