more
more

Reputation: 133

React get select values by name array

I can take name and name's value on html select attribute like that:

onChange = e => {
    this.setState({ [e.target.name]: e.target.value });
};

<select name="gender" onChange={this.onChange}>
      <option selected>Choose</option>

If I print it, it's like that gender:"woman". But I have one more select which name="gender" and I want to take them as array.If I use one more select without changing onChange method, print will like gender:"man" (last select's value). I research on internet and I can't find anything for this issue.

Upvotes: 0

Views: 124

Answers (3)

ravibagul91
ravibagul91

Reputation: 20755

If my understanding is correct, then you have 2 select with name="gender" and you want to store their value's in a single array.

You must have state to store array,

state = {
    geneder: []
}

Your onChange handler should be this,

onChange = (e) => {
  this.setState({
     [e.target.name]: [...this.state[e.target.name], e.target.value]
  })
}

Demo

Upvotes: 2

syjsdev
syjsdev

Reputation: 1336

const data = [
  {
    name: 'gender',
    data: ["woman", "man"],
  },
  {
    name: 'age',
    data: [18, 19],
  },
];
class Application extends React.Component {
  state = {
    data: []
  };
  
  onChange = (e) => {
  this.setState({data: [...this.state.data, {[e.target.options[e.target.selectedIndex].getAttribute('name')]: e.target.value}]});
  };
  
  render() {
    return (
      <div>
        <select onChange={this.onChange}>
          <option selected> Choose </option>
          {data.map(pitem => pitem.data.map(item => <option name={pitem.name}>{item}</option>))}
        </select>
        <div>{this.state.data}</div>
      </div>
    );
  }
}
React.render(<Application /> , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/react.min.js"></script>
<div id="app"></div>

Upvotes: 0

Ricardo Gonzalez
Ricardo Gonzalez

Reputation: 1879

Have you tried with event persist? Docs [ https://en.reactjs.org/docs/events.html ]

 onChange = e => {
    e.persist()
    this.setState({ [e.target.name]: e.target.value });
  };

or assigning the value of the name to a varialble

 onChange = e => {
   let name = e.target.name; 
   this.setState({ [name]: e.target.value });
  };

Upvotes: 1

Related Questions