Reputation: 1844
I am in the process of refactoring code from a React-Flux-Bootstrap app to Redux with Material-ui. What I would really like to do is have a form that starts with one input to begin with (i.e. title) and then be able to add multiple extra inputs by clicking on a button. These inputs will all be the same but obviously will need to be differentiated between (i.e. name).
Ideally I would like to be able to be able to enter in as many names as I want, collect them as an array and then send them back to my database. I am more concerned with actually creating the form itself and the code for collecting the inputs.
If someone could give me a quick example as to how I might start going about achieving this I would very much appreciate it!
Thanks for your time
Upvotes: 1
Views: 1297
Reputation: 9523
The React "comments" tutorial has a good example of user input driving a growing list: https://facebook.github.io/react/docs/tutorial.html. You want to look at the CommentList class.
To data drive the list of form fields, you could do something like this:
getInitialState() {
return {
formFields: [{key: "one", value: "first"}, {key: "two", value: "second"}]
}
},
getOnChange(key) {
let handler = () => {
let newValue = this.refs[key].getValue()
let newState = {}
newState[key] = newValue
this.setState(newState)
}
return handler
},
render() {
return (
<Paper>
{this.state.formFields.map((item, index) => {
return (<TextField ref={item.key} key={item.key} defaultValue={item.value} onChange={this.getOnChange(item.key)}/>)
})}
</Paper>
)
}
I used a closure for onChange to demonstrate variability, but there are other ways to accomplish this.
Upvotes: 3