Hello all,
I’m trying to do the Markdown Previewer challenge in create-react-app and I’m having some trouble. My code seems to work when I navigate to the page after adding it and React automatically updates it, but once I manually refresh the page it breaks.
The specific line that breaks the code is:
document.getElementById("preview").innerHTML = marked(this.state.value);
If I transfer the code over to CodePen I’m still getting the same error.
From what I’ve read online, it looks like the error is there because this is loading before it sees the preview ID. The suggested solutions read to make sure I have the script tag at the bottom of the body of the document, but I can’t do these because a) Marked is imported via npm into create-react-app and there’s no script tag in the HTML document, b) CodePen is handling it on it’s own.
I doubt that’s why I’m actually getting the error, but that’s what I’m gathering from what I’ve read. Please correct me on this if you know the answer as well!
Anyway, I’ve provided my JSX below. If anyone has any insight on how I can get this to continue working, and then I can try and finish up the challenge, it would be much appreciated.
import marked from 'marked';
import React from 'react';
import './App.css';
class MarkdownPreviewer extends React.Component{
constructor(props){
super(props);
this.state = {
value: ""
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event){
this.setState({
value: event.target.value
});
}
render(){
document.getElementById("preview").innerHTML = marked(this.state.value);
return(
<div className="container-fluid">
<div className="row">
<div className="col-md text-center">
<h1>Markdown Previewer</h1>
</div>
</div>
<div className="row">
<div className="col-md">
<h2>Enter Markdown</h2>
<textarea id="editor" value={this.state.value} onChange={this.handleChange}/>
</div>
<div className="col-md">
<h2>Preview Markdown</h2>
<div id="preview">
</div>
</div>
</div>
</div>
);
}
}
class App extends React.Component{
render(){
return(
<MarkdownPreviewer />
);
}
}
export default App;
Thanks,
Nathan