sstur / react-rte

Pure React rich text WYSIWYG editor based on draft-js.
https://react-rte.org
ISC License
2.86k stars 430 forks source link

Programatically adding text to EditorState #394

Open robertoprizzle opened 3 years ago

robertoprizzle commented 3 years ago

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!

vitorpdasilva commented 3 years ago

have you found a solution for this @robertoprizzle ?

marcelo-tm commented 3 years ago

Having the same issue here...

marcelo-tm commented 3 years ago

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