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

Programatically adding text to EditorState

Open robertoprizzle opened this issue 5 years ago • 3 comments

Hello,

Thanks for supplying such a great package!

I'm trying to work out how to insert text into the editor state programmatically.

There are a fair number of methods that the getEditorState() method exposes, but no documentation exists on how to use them to add to the state.

Any help would be greatly appreciated!

robertoprizzle avatar Nov 24 '20 15:11 robertoprizzle

have you found a solution for this @robertoprizzle ?

vitorboccio avatar Jan 19 '21 19:01 vitorboccio

Having the same issue here...

marcelo-tm avatar Feb 05 '21 13:02 marcelo-tm

I think I managed to get it to work, here's the code for my component:

import { useState, useEffect } from 'react'
import RichTextEditor from 'react-rte'

import Container from './styles'

const toolbarConfig = {
  display: ['INLINE_STYLE_BUTTONS', 'BLOCK_TYPE_BUTTONS', 'HISTORY_BUTTONS'],
  INLINE_STYLE_BUTTONS: [
    { label: 'Bold', style: 'BOLD', className: 'custom-css-class' },
    { label: 'Italic', style: 'ITALIC' },
    { label: 'Underline', style: 'UNDERLINE' },
  ],
  BLOCK_TYPE_BUTTONS: [
    { label: 'UL', style: 'unordered-list-item' },
    { label: 'OL', style: 'ordered-list-item' },
  ],
}

function RichTextField({ label, value, onChange }) {
  const [editorState, setEditorState] = useState(
    RichTextEditor.createEmptyValue(),
  )

  useEffect(() => {
    setEditorState(RichTextEditor.createValueFromString(value, 'html'))
  }, [])

  function handleValueChange(editorValue) {
    setEditorState(editorValue)
    if (onChange) onChange(editorValue)
  }

  return (
    <Container>
      <p className="label">{label}</p>
      <RichTextEditor
        value={editorState}
        onChange={handleValueChange}
        toolbarConfig={toolbarConfig}
      />
    </Container>
  )
}

export default RichTextField

marcelo-tm avatar Feb 05 '21 14:02 marcelo-tm