Change select item onChange not triggering

I am creating a select

React component that can be used in many forms. For some reason, the event onChange

doesn't fire.

Here is the element (missing proptypes and default props):

var Select = React.createClass ({
  getInitialState() {
    return {
      value: null,
    }
  },

  componentWillReceiveProps(props) {
    if (props.defaultValue) {
      this.setState({value: props.defaultValue})
    }
  },

  render() {
    var formClass = this.props.error ? "form-group has-error" : "form-group"
    var validationMsg = this.props.error ? <span className="help-block"><small>{this.props.error}</small></span> : null

    var labelClass = 'control-label col-md-' + this.props.labelWidth
    var inputWidth = 12 - this.props.labelWidth
    var widthClass = 'col-md-' + inputWidth

    return (
      <div className={formClass}>
        <label className={labelClass}>{this.props.label}</label>
        <div className={widthClass}>
          <div className="input-wrapper">
            <select ref="mySelect" className={this.props.className}
                    multiple={this.props.multiple}
                    value={this.state.value}
                    onChange={this._onchange}>
              {
                this.props.options.map((option, index) => {
                  return <Option key={index} value={option.value} text={option.text} />
                })
              }
            </select>
          </div>
          {validationMsg}
        </div>
      </div>
    )
  },

  getValue() {
    if (this.props.multiple) {
      var selected = [];
      for ( var i = 0; i < this.refs["mySelect"].selectedOptions.length; i++) {
        selected.push(this.refs["mySelect"].selectedOptions[i].value)
      }
      return selected
    }
    return this.state.value
  },

  _onchange(event) {
    console.log('hi')
    this.setState({value: event.target.value})
  }
})

      

I added a console.log

hardcoded string instruction to the function and never prints it to the console.

Things I've tried:

onchange={this._onchange}

onChange={this._onchange.bind(this)}

onChange={(evt) => this._onchange(evt)}

onChange={function(e) {console.log('test')}}

In case it matters, here's the component Option

:

var Option = React.createClass ({
  propTypes: {
    value: React.PropTypes.any.isRequired,
    text: React.PropTypes.string.isRequired,
  },

  render() {
    return (<option value={this.props.value}>{this.props.text}</option>)
  }
})

      

Questions I've looked at:

Select onChange reaction not working

My onChange is not working with react

OnChange event using React JS for dropdown

The input signal will not react to the change

https://jsfiddle.net/69z2wepo/9958/ (it works here!)

onChange callback not firing in React component

+3


source to share





All Articles