Ad

How To Get Values From Same Input Type From Multiple Fields In React?

I have to get the values from same input type (eg: email type) this is in my render() method:

            <TextField
              value={email}
              className={classes.textField}
              onChange={this.handleChange('email')}
            />
            <TextField
              value={email}
              className={classes.textField}
              onChange={this.handleChange('email')}
            />
            <TextField
              value={email}
              className={classes.textField}
              onChange={this.handleChange('email')}
            />
            <p onClick={this.addMemberHandler}> ADD MORE EMAIL ADDRESSES</p>

I don't have limit to this. state values, handleChange, addMemberHandler methods

          state = {
           addOneMoreEmail: false,
           emailCounter: 0,
           email: ''
         };

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

       addMemberHandler = () => {
         this.setState({
           addOneMoreEmail: true
         });
       };

My question is: How can I get all the emails (which user has entered) in my state, so that onSubmit I will sent all the emails in an array?

Basically how can I maintain different state for each email dynamically?

Ad

Answer

You provide only one state field for multiple - well - states. This cannot work. You could either have multiple fields like state.email1, state.email2 etc or you can use an array.

This should do it using an array of emails as state:

state = {
  emails: []
}

render () {
  const emails = this.state.emails
  return (
    <div>
      {emails.map((email, index) => (
        <Textfield
          key={index}
          value={email}
          onChange={event => this.setState({
            emails: [
              ...emails.slice(0, index),
              event.target.value,
              ...emails.slice(index + 1) 
            ]
          })
      ))}
      <p onClick={() => this.setState({emails: [...emails, '']})}>add email</p>
    </div>
  )
}

This will give you a dynamic list of emails, which can be expanded by clicking the <p>.

Please note, that using the index as key is discouraged: https://reactjs.org/docs/lists-and-keys.html.

Ad
source: stackoverflow.com
Ad