Textarea not updating in my Markdown Previewer

30 Views Asked by At

I've been working on this Markdown Previewer to improve my skills in JavaScript and React and I've run into an issue I can't solve. I don't know if I've just been staring at it too long or what.

Everything loads properly, the only issue is that when I try to type something into the textarea, it won't let me change anything in it. It isn't set to read only, so I'm really unsure as to what it is doing this.

Component

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      markdown: initialMarkdown
    };
    this.handleChange(this.handleChange.bind(this));
  }

  handleChange(event) {
    try {
      this.setState({
        markdown: event.target.value
      });
    } catch (e) {}
  }

  render() {
    return (
      <div>
        <div className="input">
          <div className="header">Editor</div>
          <textarea
            id="editor"
            value={this.state.markdown}
            onChange={this.handleChange}
          ></textarea>
        </div>
        <div className="output">
          <div className="header">Preview</div>
          <div
            id="preview"
            dangerouslySetInnerHTML={{ __html: marked(this.state.markdown) }}
          ></div>
        </div>
      </div>
    );
  }
}

//Rendering to HTML
ReactDOM.render(<App />, document.getElementById("app"));

I've scoured a few different threads and subreddits and what not, but I have found nothing to solve my issue. Anybody got any ideas?

1

There are 1 best solutions below

0
Drew Reese On

handleChange is throwing an error when it's called:

TypeError: Cannot read properties of undefined (reading 'setState')

The issue is that the this of the class component isn't correctly bound to the callback function so it is simply undefined in the callback.

In the constructor change

this.handleChange(this.handleChange.bind(this));

to

this.handleChange = this.handleChange.bind(this);

or convert handleChange to an arrow function

handleChange = (event) => {
  try {
    this.setState({
      markdown: event.target.value
    });
  } catch (e) {
    console.error(e);
  }
}