Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cursor position when creating a state from a string with Draft.js

How can I set the cursor position after creating an EditorState with content and some decorators on Draft.js. It always starts on the position 0.

This is what happens:

enter image description here

This is what I want:

enter image description here

Here is how I am creating the state.

  constructor(props) {
    super(props)
    this.state = { editorState: this.getEditorState() }
  }

  getEditorState() {
    const { reply: { channel, userAccount } } = this.props
    const content = this.getEditorContent({ channel, userAccount })
    const decorators = this.getEditorDecorators(channel)
    return EditorState.createWithContent(content, decorators)
  }

  getEditorContent({ channel, userAccount }) {
    const content = channel && channel.prefill(userAccount)
    return ContentState.createFromText(content || '')
  }

  getEditorDecorators({ decorators }) {
    return getDecorators(decorators || [])
  }
like image 345
Rafael Berro Avatar asked Nov 23 '25 22:11

Rafael Berro


1 Answers

After reading the issue 224 from Draft.js repository, I've found a static method called moveSelectionToEnd. Everything that I need to do is wrap the brand new state with this method, this way.

  getEditorState() {
    const { reply: { channel, userAccount } } = this.props
    const content = this.getEditorContent({ channel, userAccount })
    const decorators = this.getEditorDecorators(channel)
    const state = EditorState.createWithContent(content, decorators)
    return EditorState.moveSelectionToEnd(state)
  }
like image 148
Rafael Berro Avatar answered Nov 25 '25 10:11

Rafael Berro