Yanick Rochon
Yanick Rochon

Reputation: 53546

No "onChange" event on materialize select element

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?

Upvotes: 1

Views: 3537

Answers (1)

Yanick Rochon
Yanick Rochon

Reputation: 53546

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

Upvotes: 6

Related Questions