2

I use react-draft-wysiwyg editor which's state should be controlled by Formik. The idea is the Formik value being a string, so Editor state is converted to HTML with stateToHTML and set as value, and when received from Formik, it is converted form HTML to EditorState. The value being passed back and forth, and not controlled by Editor itself, is essential due to be able to reset the form with Formik methods. Also, the value needs to be sent from the form as a string, the backend shouldn't be aware what kind of an editor is used on the frontend.

The problem is that, although the string with html is passed to and from Formik well, the updating data goes wrong. After updating string, the cursor returns to the very beginning of the editor window (input?) and adds the newly typed string in front of the string. It looks like I was typing from right to left. However, backspace and delete keys works as intended.

Formik uses it like here

<Field name='wysiwyg' label='Wysiwyg' component={Editor} />

This is the way Editor is set

const setEditorState = (html) => {
  const blocksFromHTML = convertFromHTML(html || '')
  if (blocksFromHTML.contentBlocks !== null) {
    const state = ContentState.createFromBlockArray(
      blocksFromHTML.contentBlocks,
      blocksFromHTML.entityMap
    )
    return EditorState.createWithContent(state)
  }
  return EditorState.createEmpty()
}

class XXX extends react.Component {
onEditorStateChange = (editorState) => {
    const contentState = editorState.getCurrentContent()
    this.props.form.setFieldValue(this.props.field.name, stateToHTML(contentState)) //stateToHTML imported from draft-js-export-html 
  }


render () {
   return (
      <Editor
        editorState={setEditorState(this.props.field.value)}
        onEditorStateChange={this.onEditorStateChange}
        ...
      />
    )
  }
}
Dune
  • 674
  • 1
  • 9
  • 19

1 Answers1

4

Just incase someone is still looking for a solution to integrate DraftJS with Formik. I found this very useful codesandbox project that does this.

loQ
  • 2,147
  • 18
  • 21
  • 2
    The codesandbox is using `formik v-0.9, can you shed any light on if there's a more recent implementation or would it be safe to still follow the example despite to old versioning? – DJ2 Oct 02 '19 at 02:58