0

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?

1 Answer 1

1

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.

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

2 Comments

Could you please describe onChange handle please? I am not able to understand that.
The function updates the state.emails Array at position "index". to update the array, the array spread operator is used. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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.