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?
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.
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?