I’m trying to learn draftjs. I’ve made an example where if you click a button it’s supposed to insert some text in the editor, but I can’t understand why it isn’t working, clicking the button has no visible effect.
import React, { Component } from "react";
import { Editor, EditorState, Modifier, SelectionState } from 'draft-js';
import 'draft-js/dist/Draft.css';
export class TextEditor extends Component {
constructor(props) {
super(props);
this.state = {editorState: EditorState.createEmpty() };
this.focus = () => this.refs.editor.focus();
this.toggleText=this.toggleText.bind(this);
}
toggleText(){
let currentEditorState=this.state.editorState;
let selectionState = currentEditorState
.getSelection()
.set('anchorOffset', 0)
.set('focusOffset', 5);
let newContentState = Modifier.replaceText(
currentEditorState.getCurrentContent(),
selectionState,
'Your new text here'
);
let newEditorState = EditorState.push(currentEditorState,
newContentState,
'replace-text');
this.setState({ editorState: newEditorState });
}
render() {
return (<div>
<div onClick={this.focus} className="TextEditor">
<button onClick={()=>this.toggleText()}>Toggle</button>
<Editor
editorState={this.state.editorState}
onChange={x=>this.setState({editorState:x})}
ref="editor"
/>
</div>
</div>);
}
}