HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

OnChange event using React JS for drop down

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
onchangedropreacteventusingfordown

Problem

var MySelect = React.createClass({
     change: function(){
         return document.querySelector('#lang').value;
     },
     render: function(){
        return(
           
               
                  Select
                  Java
                  C++
               
               
               
           
        );
     }
});

React.render(, document.body);


The onChange event does not work.

Solution

The change event is triggered on the ` element, not the 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(
           
               
                  Select
                  Java
                  C++
               
               
               {this.state.value}
           
        );
     }
});

React.render(, document.body);


Also note that

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
` element then simply put inside of it, like you would do with any static content.

Learn more about event handling, state and form controls:

  • http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html



  • http://facebook.github.io/react/docs/forms.html

Code Snippets

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);

Context

Stack Overflow Q#28868071, score: 452

Revisions (0)

No revisions yet.