Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple choose file button

What I want to achieve is have another choose file button to upload another file only after a file is attached to the first one.

I am doing the following to render my button:

<FormControl
   type="file"
   accept=".jpg"
   onChange={this.onImageUpload}
/>

What I tried is to have an array of any with one null value, to begin with. When onImageUpload is evoked I push the values on the file into the array. Now I have 2 elements in the array, null and the file. I try to iterate over the length of the array and render that many choose a file to upload buttons. The problem is I lose the file names next to the button on doing this. How can I add a new button without losing the filename on the previous one?

After one file upload

Before one file upload

like image 940
Tee F Avatar asked Dec 20 '25 04:12

Tee F


1 Answers

What you could do is have an array state declared in the constructor with a single FormControl at index 0 like this,

constructor(props) {
   this.state = {
      FormControls: [
       <FormControl
         type="file"
         accept=".jpg"
         onChange={this.onImageUpload}
       />
     ]
   }
}

and then insert another to the array whenever an image is uploaded (onChange is triggered) like this,

onImageUpload() {
   let formArray = this.state.FormControls;
   formArray.push(<FormControl
         type="file"
         accept=".jpg"
         onChange={this.onImageUpload}
       />
   );
   this.setState({FormControls: formArray})
}

and finally, have the top parent include all the input (FormControl) like this,

<ParentView>{this.state.FormControls}</ParentView>

Also, don't forget to add a new and unique ref to the FormControl while adding it to the array.

like image 76
Nilesh Singh Avatar answered Dec 21 '25 18:12

Nilesh Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!