1

I am trying to upload a file in reactjs, I want to display in the console, but when I click on upload button it gives me

"TypeError: Cannot read property 'state' of undefined"

Here is my code:

constructor(props) {
        super(props);

this.state = {
  selectedFile: null
};

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

fileSelectedHandler(event) {
  this.setState({
    selectedFile: event.target.files[0]
  })
}

handleUpload() {
  console.log(this.state.selectedFile)
}
render() {
 return (
    <div class="group">
      <input type="file" name="file" id="file" onChange={this.fileSelectedHandler} />
      <button onClick={this.handleUpload}> Upload </button>
    </div>
    )
}

I am getting the error at: console.log(this.state.selectedFile)

Nirav Panchal
  • 59
  • 2
  • 7

1 Answers1

1

There are two ways to fix this either bind handleUpload to the correct this content or define your function in below format

handleUpload = () => {
console.log(this.state.selectedFile)
}
Karan Garg
  • 1,083
  • 10
  • 9