0

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.

1
  • Hi more, check my solution and let me know if that helps. Commented Sep 25, 2019 at 2:50

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

what's different between them?
The persist method allows the code to use the value of the async synthetic event. And if you set a new variable this will store the value in the memory
0

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>

2 Comments

what if I want to use for 2 different names? I mean genders=["man","woman"] ages=[18,19]
It's getting last values from age and gender not array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.