Skip to content
Advertisement

OnChange event using React JS for drop down

var MySelect = React.createClass({
     change: function(){
         return document.querySelector('#lang').value;
     },
     render: function(){
        return(
           <div>
               <select id="lang">
                  <option value="select" onChange={this.change}>Select</option>
                  <option value="Java" onChange={this.change}>Java</option>
                  <option value="C++" onChange={this.change}>C++</option>
               </select>
               <p></p>
               <p value={this.change}></p>
           </div>
        );
     }
});

React.render(<MySelect />, document.body);

The onChange event does not work.

Advertisement

Answer

The change event is triggered on the <select> element, not the <option> element. However, that’s not the only problem. The way you defined the change function won’t cause a rerender of the component. It seems like you might not have fully grasped the concept of React yet, so maybe “Thinking in React” helps.

You have to store the selected value as state and update the state when the value changes. Updating the state will trigger a rerender of the component.

var MySelect = React.createClass({
     getInitialState: function() {
         return {
             value: 'select'
         }
     },
     change: function(event){
         this.setState({value: event.target.value});
     },
     render: function(){
        return(
           <div>
               <select id="lang" onChange={this.change} value={this.state.value}>
                  <option value="select">Select</option>
                  <option value="Java">Java</option>
                  <option value="C++">C++</option>
               </select>
               <p></p>
               <p>{this.state.value}</p>
           </div>
        );
     }
});

React.render(<MySelect />, document.body);

Also note that <p> elements don’t have a value attribute. React/JSX simply replicates the well-known HTML syntax, it doesn’t introduce custom attributes (with the exception of key and ref). If you want the selected value to be the content of the <p> element then simply put inside of it, like you would do with any static content.

Learn more about event handling, state and form controls:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement