Skip to content Skip to sidebar Skip to footer

Onchange Callback Not Firing In React Component

My onChange() function does not run unless I use jQuery for some reason. The reason why I have to add the onChange listener in componentDidMount() is because I'm using MaterializeC

Solution 1:

The problem is that the plugin is emitting a custom change event. React's event system doesn't recognize custom events (not sure why).

In this case a manual change listener is the right solution. The way you improve this is by abstracting the select element to an 'atom'.

classSelectextendsReact.Component {
  static propTypes = {
    value: React.PropTypes.string,
    options: React.PropTypes.arrayOf(
      React.PropTypes.shape({
        text: React.PropTypes.string.isRequired,
        value: React.PropTypes.string.isRequired,
      })
    ).isRequired
  };
  constructor() {
    super();
    this.onChange = this.onChange.bind(this);
  }

  onChange(e) {
    this.props.onChange(e.target.value);
  }

  componentDidMount() {
    let select = this.refs.select;
    select.addEventListener('change', this.onChange, false);
  }

  componentWillUnmount(){
    let select = this.refs.select;
    select.removeEventListener('change', this.onChange, false);  
  }

  render() {
    let classes = 'input-field col s10 offset-s1 l3';

    return (
      <divclassName={classes}><selectref="select"value={this.props.value}>
          {this.props.options.map((x) => {
            return <optionkey={x.value}value={x.value}>{x.text}</option>;
          })}
        </select></div>
    );
  }
}

You can then use this in InspectionMode or anywhere else in your UI.

classInspectionModeextendsReact.Component{
  constructor(props) {
    super(props);
    this.onChange = this.onChange.bind(this);
    this.value = 'selected';
    this.state = { inspectionTime: 0 };
  }

  onChange(inspectionTime) {
    this.setState({ inspectionTime });
  }

  render() {
    return (
      <div>
        <Select 
          value={this.state.inspectionTime}
          onChange={this.onChange}
          options={[
            {value: '0', text: 'None'},
            {value: '5', text: '5 seconds'},
            {value: '10', text: '10 seconds'},
            {value: '15', text: '15 seconds'},
          ]}
        />
        <label>Inspection Time</label>
      </div>
    );
  }
}

Post a Comment for "Onchange Callback Not Firing In React Component"