Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when using {react-select} Cannot read property 'name' of undefined

I am very beginning to reactJS and front end

I added react-select npm for my dropdown like below, before added react-select everything is working fine. How to define name in Select?

<div className="container">
            <div className="row">
              <div className="col-md-4" />
              <div className="col-md-4">
                <Select
                  options={this.state.allGenres}
                  onChange={this.props.onDataChange}
                  name="genre"
                />
              </div>
              <div className="col-md-4" />
            </div>
          </div>

this is my array,

 var Data = response.data;
    const map = Data.map((arrElement, index) => ({
      label: arrElement,
      value: index
    }));

example:

[
    {
        "label": "Action",
        "value": 0
    },
    {
        "label": "Comedy",
        "value": 1
    },
    {
        "label": "Documentary",
        "value": 2
    }
]

error message coming in here,

   dataChange(ev, action) {
    this.setState({
      [ev.target.name]: ev.target.value
    });
  }

render()

 render() {
    return (
      <Movie
        onPostData={this.postData.bind(this)}
        onDataChange={this.dataChange.bind(this)}
      />
    );
  }

Error

Uncaught TypeError: Cannot read property 'name' of undefined at Movies.dataChange

like image 241
BIS Tech Avatar asked Oct 25 '25 15:10

BIS Tech


2 Answers

You expect the first argument in react-select´s onChange method to be an event object, but it isn't.

The first argument is the selected option (or options if you have isMulti set). There is also a second argument which is an object with the following attributes:

  • action: The action which triggered the change
  • name: The name given to the Select component using the name prop.

So if you want to use the name:

onDataChange={(value, action) => {
    this.setState({
        [action.name]: value
    })
}}

Reference in source code

I worked around this method and it worked.

handleSelectChange: function(name) {
    return function(newValue) {
        // perform change on this.state for name and newValue
    }.bind(this);
  },

render: function() {
   return (
      <div>
        <Select ...attrs...  onChange={this.handleSelectChange('first')} />
        <Select ...attrs...  onChange={this.handleSelectChange('second')} />
      </div>);
  }
like image 30
Arashdeep Singh Avatar answered Oct 27 '25 05:10

Arashdeep Singh