Allu Manikyam
Allu Manikyam

Reputation: 461

How to get the value from the material select dropdown in react

I am trying to get the value from the select drop down through onChange action but the function was not calling in react.

handleInputChange(event) {
  alert("testing")
  event.persist();
  this.setState((state) => {
    state.registerForm[event.target.name] = event.target.value
  });
}
componentWillMount() {
  console.log("executed")
  $(document).ready(function() {
    $('.dropdown-button').dropdown({
      constrainWidth: false,
      hover: true,
      belowOrigin: true,
      alignment: 'left'
    });
    $('select').material_select();
    $('.dropdown-button').dropdown({
      constrainWidth: false,
      hover: true,
      belowOrigin: true,
      alignment: 'left'
    });
    $('.button-collapse').sideNav();

  });
}
<div className="col-md-6 pl-0">
  <select id="countryCode" name="countryCode" onChange={this.handleInputChange}>
    <option value="Code" disabled selected required>Code</option>
    <option value="Option 1">Option 1</option>
    <option value="Option 2">Option 2</option>
    <option value="Option 3">Option 3</option>
  </select>
  <div className="errorField mt-18">{this.state.registerFormError.countryCode}</div>
</div>

I have tried to get the value from the select dropdown.the function was not called.I did not find what is the problem in my code.

Upvotes: 0

Views: 513

Answers (2)

Allu Manikyam
Allu Manikyam

Reputation: 461

Using delegated event fixes the problem for me.

$('#pickerContainer').on('change', 'select', function(){ console.log("got you"); });

This link was fixed my problem.please refer to the following link https://github.com/facebook/react/issues/3667

Upvotes: 0

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You could add event listener on change event using jquery

$('select')
  .material_select()
  .change(this.handleInputChange);
  // assuming you have binded `handleInputChange` in constructor
  // if not you need to add `this.handleInputChange = this.handleInputChange.bind(this)`
  // line of code to constructor or make `handleInputChange` to be an arrow function

Also you don't need to directly mutate state in setState function. You need to return an object to be merged with the state.

handleInputChange(event) {
  alert("testing")
  this.setState((state) => {
    return {
      registerForm: {
        ...state.registerForm,
        [event.target.name]: event.target.value
      }
    }
  });
}

Upvotes: 2

Related Questions