react-rte icon indicating copy to clipboard operation
react-rte copied to clipboard

Insert text

Open MarinusDR opened this issue 8 years ago • 4 comments

I try to insert text in te editor. In Draft.js one can use: const editorState = this.state.editorState; const selection = editorState.getSelection(); const contentState = editorState.getCurrentContent(); const ncs = Modifier.insertText(contentState, selection, 'my text'); const es = EditorState.push(editorState, ncs, 'insert-fragment'); this.setState({ editorState: es }); But I can not get this right in react-rte. Has sombody an idea?

MarinusDR avatar Nov 24 '16 14:11 MarinusDR

Hi @MarinusDR - this was bugging me all day today and I think I found a way... I don't know if this is the "right" way to do this, but it's a way:

First, drop a React ref on your RichTextEditor component:

<RichTextEditor
  ... // whatever other props you gave it
  ref="theEditor"
/>

Now, wherever you were writing that code from your comment (you'll still need all of that Modifier.insertText and EditorState.push) but instead of this.setState({ editorState: es }); do something like this:

this.refs.theEditor._onChange( es );

This will trigger the _onChange that is internal to the react-rte RichTextEditor component, which will in turn trigger the onChange prop that was passed in to it, which will in turn take care of your this.setState({ editorState: es }); implicitly / as if the operation was added directly.

Hope this helps! (maybe someone can tell us what the "right" way is!)

Percipient24 avatar Mar 21 '17 18:03 Percipient24

@MarinusDR @Percipient24 Hello, this code works great for me:

insertText = (text = 'example') => {
  const newValue = `${this.state.value.toString('html')} <p>${text}</p>`

  this.setState({
    value: RichTextEditor.createValueFromString(newValue, 'html'),
  })
}

ArekRado avatar May 15 '17 08:05 ArekRado

see https://github.com/sstur/react-rte/issues/247

sandorvasas avatar Nov 18 '17 13:11 sandorvasas

Hi, is there any updated way to do this?

I tried the solution from @ArekRado and the one from #247 but I am getting an [Object object] as an inserted content.

image

polcats avatar Jan 13 '21 10:01 polcats