I’m trying to incorporate the lifecycle method componentDidMount into my markdown previewer. At the moment I have one stateful class component where the handleChange method is housed. The Editor component is separate:
class App extends Component {
constructor(props){
super(props);
this.state = {
value: OnLoad
};
this.handleChange = this.handleChange.bind(this);
}
handleChange (event) {
this.setState({
value: event.target.value
});
}
render() {
const title="React Markdown Previewer";
const subtitle="Edit textarea to change preview";
return (
<div className="contents">
<Title title={title} subtitle={subtitle}/>
<Main value={this.state.value} handleChange={this.handleChange}/>
</div>
);
}
}
export default App;
//separate file
class Editor extends React.Component {
constructor(props) {
super(props);
}
render () {
return (
<div className="editor-box" style={style}>
<h2 style={style.heading}>Type markdown here</h2>
<textarea id="editor" className="resizeable" style={style.box} rows="27" onChange={this.props.handleChange} >{this.props.value}</textarea>
</div>
);
}
}
export default Editor;
I don’t know to pass the event listener change
as props to Main
and then Editor
if it is added in componentDidMount
. I have tried the following code:
componentDidMount() {
const editor = document.getElementById('editor');
editor.addEventListener('change', this.handleChange);
}
in both the App and Editor components but both fall apart when I remove the onChange
declaration from the render methods.
If possible I’d like to have the Editor
component as a functional component as I had it before trying to add the lifecycle method.