diff --git a/src/index.tsx b/src/index.tsx index a56aca86..ac2ec75f 100755 --- a/src/index.tsx +++ b/src/index.tsx @@ -47,6 +47,8 @@ export default class SimpleMDEEditor extends React.PureComponent< SimpleMDEEditorProps, SimpleMDEEditorState > { + private elementWrapperRef: any; + static defaultProps = { events: {}, onChange: noop, @@ -91,7 +93,9 @@ export default class SimpleMDEEditor extends React.PureComponent< } componentWillUnmount() { - this.removeEvents(); + if (this.editorEl !== null && this.editorEl !== undefined) { + this.removeEvents(); + } } createEditor = () => { @@ -121,16 +125,11 @@ export default class SimpleMDEEditor extends React.PureComponent< }; addEvents = () => { - const wrapperId = `${this.id}-wrapper`; - const wrapperEl = document.getElementById(`${wrapperId}`); - - this.editorEl = wrapperEl!.getElementsByClassName("CodeMirror")[0]; - this.editorToolbarEl = wrapperEl!.getElementsByClassName( - "editor-toolbar" - )[0]; + this.editorEl = this.elementWrapperRef; + this.editorToolbarEl = this.elementWrapperRef.getElementsByClassName("editor-toolbar")[0]; - this.editorEl.addEventListener("keyup", this.eventWrapper); - this.editorEl.addEventListener("paste", this.eventWrapper); + this.editorEl!.addEventListener("keyup", this.eventWrapper); + this.editorEl!.addEventListener("paste", this.eventWrapper); this.editorToolbarEl && this.editorToolbarEl.addEventListener("click", this.eventWrapper); @@ -166,6 +165,10 @@ export default class SimpleMDEEditor extends React.PureComponent< this.simpleMde!.codemirror.setOption("extraKeys", this.props.extraKeys); } }; + + private buildWrapperRef = (e: any) => { + this.elementWrapperRef = e; + }; render() { const { @@ -182,7 +185,7 @@ export default class SimpleMDEEditor extends React.PureComponent< ...rest } = this.props; return ( -