1

I know this question has been asked several times, however I went over the answers and I could not find a resolution to my problem.

I have a very basic class component that is just loading an external HTML file and reading its contents, however for some reason I am getting this.setState is not a function after the actual HTML is loaded, and I cannot figure out why yet.

This is my code:-

import React from "react";

class ReadHtml extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            innerText: ''
        };
        this.handleFileSelect = this.handleFileSelect.bind(this);
      }


    handleFileSelect = (evt) => {
        evt.preventDefault();
        var file = evt.target.files[0]; // File inputs are an array - get the first element
        var reader = new FileReader();

        reader.onload = function(e) {
          // Render the supplied file
          document.getElementById('displayPage').innerHTML = e.target.result;
          this.setState({
              innerText: e.target.result
          });
        };

        // Read in the HTML file.
        reader.readAsText(file);
      };

    render() {
        return (
          <div>
            Select a file : <input type="file" onChange={(e) => this.handleFileSelect(e)} /><br/><br/>
            <div id="displayPage">Display the Html Page here</div>
          </div>
        )
      }

}

export default ReadHtml;

Any help will be really very much appreciated!

2 Answers 2

2

there is a scope issue you can try this code. Or you can bind the function.

reader.onload = (e) =>{
      // Render the supplied file
      document.getElementById('displayPage').innerHTML = e.target.result;
      this.setState({
          innerText: e.target.result
      });
    };
Sign up to request clarification or add additional context in comments.

Comments

1

You could try to change your handleFileSelect function with this :

    handleFileSelect = (evt) => {
        evt.preventDefault();
        var file = evt.target.files[0];
        var reader = new FileReader();

        reader.onload = (e) => { //CHANGES
          document.getElementById('displayPage').innerHTML = e.target.result;
          this.setState({
              innerText: e.target.result
          });
        };

        // Read in the HTML file.
        reader.readAsText(file);
      };

Basically, when you are creating a new function (here your reader.onload = function()), the this is bind to this function. With the arrow functions, the this stays with your React Class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.