React.js: Add/Remove input field on click of a button:
When a user click Add, I want a new input field to be added.
The name property is changing for every input, by increment the number in the middle:
document-0-document document-1-document
I receive the following error:
"TypeError: this is undefined var arr = this.state.documents;"
I have an idea what is creating the error but I didn't found a fix.
HTML Code.
<fieldset class="fieldset">
<input type="file" name="document-0-document">
<div class="more-documents">
<input type="file" name="document-1-document">
<button data-reactid=".0.1">Add</button>
</div>
</fieldset>
Main Component code:
class DocumentsFieldSet extends Component{
constructor(props){
super(props);
this.state = {documents:[]}
}
add(i) {
var arr = this.state.documents;
arr.push(i);
this.setState({documents: arr});
}
eachDocument () {
return <DocumentInput key={i}/>
}
render (){
return (
<div>
{this.state.documents.map(this.eachDocument)}
<button onClick={this.add.bind()}>Add</button>
</div>
)
}
}
ReactDOM.render(<DocumentsFieldSet/>, document.querySelector ('.more- documents'))
Component Code
class DocumentInput extends Component {
render() {
return <input type="file" name="document-{i}-document" ref="" />;
}
}
export default DocumentInput;