Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get selected value onChange of react redux-form drop down

I am using react redux form Fields and I have drop down of classes. I am able to select any class from drop down. but the issue is that whenever I select any value (class) from drop down I want to trigger action onChange. When I trigger action with on change drop down values does not set and it does not show selected value. I am using following lines of code

<Field name="class._id" component="select" className="form-control" onChange={this.onChange.bind(this)} >
              <option value="">Select class...</option>
              {this.props.classes.map(Class =>
              <option value={Class._id} key={Class._id} >{Class.name}</option>)}
</Field>

here is onChange function

 onChange(){
     console.log(" Triggered")
  }

If I do not set onChange event my drop down works correctly and it shows selected value correctly with proper text. but I want to call function whenever use select any value

like image 728
Muhammad Ateek Avatar asked Jul 26 '16 11:07

Muhammad Ateek


People also ask

How do you get onChange value in React?

To handle the onChange event on a select element in React: Set the onChange prop on the select element. Keep the value of the selected option in a state variable. Every time the user changes the selected option, update the state variable.

How do you get the selected value of select option in React?

To fetch the selected value from the select element, you can use the onChange event handler prop. Just like the input or textarea elements, you can use the onChange event handler to get the value from the event object. Now, make this select input element controlled by using the state to pass the value.

How do you use React select in a form?

Basic usage of react-selectjs import React from 'react'; import Select from 'react-select'; ... With those two packages imported, we will be able to have access to the react-select ( <Select />) and also extend the React. Component class. In traditional HTML, the <select> tag houses multiple options and values.


2 Answers

Can you give more context for this code, perhaps putting the whole component (and any modules or containers or whatever) in a JSBin or Fiddle? That will help SO posters better know how to help you. That said, it looks like your code is correct. You can get the value out of the select kind of like this:

onChange(event) {
  console.log(event.target.value);
}

Does that help?

like image 78
jasongonzales Avatar answered Nov 03 '22 23:11

jasongonzales


May be you should better use fields prop of redux and standard html elements?

const {fields} = this.props
<select {...fields.class} onChange={this.handleChange}>
...

handleChange(event) {
    // do your stuff
    this.props.fields.class.onChange(event)
}
like image 2
Eugene Zinin Avatar answered Nov 04 '22 01:11

Eugene Zinin