Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  193] [ 7]  / answers: 1 / hits: 25941  / 8 Years ago, tue, july 26, 2016, 12:00:00

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;

More From » reactjs

 Answers
17

You have several mistakes in your example




  1. You need bind this for .add method


  2. You don't put to this.state.documents array index


  3. Inside DocumentInput there is no i variable






class DocumentInput extends React.Component {
render() {
return <input
type=file
name={ `document-${ this.props.index }-document` }
/>;
}
}

class DocumentsFieldSet extends React.Component{
constructor(props){
super(props);

this.state = {
documents: []
}

this.add = this.add.bind(this);
}

add() {
const documents = this.state.documents.concat(DocumentInput);
this.setState({ documents });
}

render () {
const documents = this.state.documents.map((Element, index) => {
return <Element key={ index } index={ index } />
});

return <div>
<button onClick={ this.add }>Add</button>

<div className=inputs>
{ documents }
</div>
</div>
}
}

ReactDOM.render(
<DocumentsFieldSet />,
document.getElementById('container')
);

.inputs {
margin: 5px 0;
padding: 10px;
border: 2px solid #000;
}

<script src=https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js></script>
<div id=container></div>




[#61250] Friday, July 22, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianod

Total Points: 667
Total Questions: 106
Total Answers: 92

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
lucianod questions
;