3

I'm trying to implement a solution where you hide the file chosen by a user for an input type of 'file'. Here is the stack article that outlines the solution: input type=file show only button

I am not able to capture the onChange event, and hence am unable to read the file. The event in the method 'saveFileToStoreOnChange' is undefined. Where did I go off the road here?

html (jsx):

<input className="invisible" type="file" id="logo"/>
<input type="button" value="Browse..." onClick={this.saveFileToStoreClick} />

Javascript:

saveFileToStoreClick(){
        $('#logo').on('change', this.saveFileToStoreOnChange());
    }

saveFileToStoreOnChange(event){
        //event is undefined
        let file = event.target.files[0];
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
nikotromus
  • 1,015
  • 16
  • 36

3 Answers3

2

You don't have the correct context in the event. Bind or use an arrow function:

onClick={(e) => this.saveFileToStoreClick(e)}

I don't know why you're binding to the event with jQuery programmatically though (or even using jQuery, or an ID selector instead of a reference). I didn't understand the reason for not having an onChange handler on the file input.

As a commenter said you're also calling the function instead of passing it in your event.

Dominic
  • 62,658
  • 20
  • 139
  • 163
  • The reason I dont have an onChange handler on the file input can be found here: http://stackoverflow.com/questions/1084925/input-type-file-show-only-button. It's the second solution I am trying to implement where the file selected is hidden. – nikotromus Dec 16 '16 at 15:27
  • the correct solution to this problem is to not use jQuery with React... – Conan Dec 16 '16 at 15:55
  • 1
    Agreed. and - I found the solution to the problem by using a simple .css class as found with the second solution here: http://stackoverflow.com/questions/6105116/anyway-to-remove-no-file-selected-from-type-file-inputs – nikotromus Dec 16 '16 at 15:58
0

You're calling this.saveFileToStoreOnChange() instead of passing the function.

Change your code to:

$('#logo').on('change', this.saveFileToStoreOnChange);

(See the removed () after the function name)

phortx
  • 849
  • 5
  • 21
0

This code may helps you

saveFileToStoreClick(){

            $('#logo').on('change', this.saveFileToStoreOnChange());
        }

    saveFileToStoreOnChange(event){


            let file = event.currentTarget.files[0];
    }
ubm
  • 636
  • 11
  • 21