1

I have this form component :

import React, { Component } from 'react'

export default class FooForm extends Component {
  updateFooSelection() {
    console.log('Something should be printed... but I see nothing :(');
  }

  componentDidMount() {
    this.initialiseWidgets();
  }

  componentDidUpdate() {
    this.initialiseWidgets();
  }

  initialiseWidgets() {
    Materialize.updateTextFields();
    $(this.refs.selectFoo).material_select();
  }

  componentWillUnmount() {
     $(this.refs.selectFoo).material_select('destroy');
  }

  render() {
    return (
      <form>
        <select id="selFoo" ref="selectFoo" onChange={ this.updateFooSelection }>
          <option value="foo">Foo</option>
          <option value="bar">Bar</option>
        </select>
      </form>
    );
  }
};

However, the function updateFooSelection is never fired at all. When inspecting the DOM, there doesn't seem to be any onchange attribute or anything like that. I tried understanding the docs, however there is no example for such element.

How can I get a change event for a select element with Materialize in React?

How come the onChange event is never fired on this element?

Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
  • Possible duplicate of [OnChange event using React JS for drop down](http://stackoverflow.com/questions/28868071/onchange-event-using-react-js-for-drop-down) – Adjit Aug 11 '16 at 18:11
  • No! The event is **not** triggered at all! It's not about having a reactive SELECT element. – Yanick Rochon Aug 11 '16 at 18:14
  • Are you using es6? Can you show a bit more of your component? – tedcurrent Aug 11 '16 at 18:19
  • @Donal this link has nothing to do with my question, it addresses issues with keystrokes and INPUT elements. My question is about selection changes that are not being triggered *at all*. – Yanick Rochon Aug 11 '16 at 18:23
  • In *updateFooSelection()* you miss a double quote at the end of the console.log, or it is a typo? – Mario Santini Aug 11 '16 at 18:33
  • @MarioAlexandroSantini yes, I'll fix it. Thanks. – Yanick Rochon Aug 11 '16 at 18:35
  • You won't find an `onchange` attribute or `change` handler on the rendered DOM element, because React uses [its own event delegation system](https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#under-the-hood-autobinding-and-event-delegation). – A. Vidor Aug 11 '16 at 18:47

1 Answers1

6

This issue explains why.

Basically, the ònChange props will simply no work, and .on('change', ... needs to be used instead.

initialiseWidgets() {
  Materialize.updateTextFields();
  $(this.refs.selectFoo).on('change', function () {
     console.log('yay!');
  }).material_select();
}
Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214