draft-js-utils icon indicating copy to clipboard operation
draft-js-utils copied to clipboard

Uncaught TypeError: this.contentState.getBlocksAsArray is not a function

Open NicholasLYang opened this issue 6 years ago • 2 comments

Getting the following error when trying to convert my state. Using draft-js plugins, but I'm not so sure that's the issue. The code is here. Relevant portions:

import { stateToHTML } from "draft-js-export-html"

  handleSubmit = () => {
    const { editorState } = this.props;
    // For testing purposes
    console.log(stateToHTML(editorState));
  }

The state when I print it out seems to be a perfectly normal immutable map. Not really sure what's going on here

NicholasLYang avatar Nov 05 '17 06:11 NicholasLYang

Okay, so turns out that you can't just give the editorState to stateToHTML. You need to give the contentState to the function. You can grab it from editorState._immutable.currentContent, but that seems a little hacky. Will try to find a better solution

Edit: duh. Just use editorState.getCurrentContent(). So in full:

  handleSubmit = () => {
    const { editorState } = this.props;
    // For testing purposes
    console.log(stateToHTML(editorState.getCurrentContent()));
  }

NicholasLYang avatar Nov 10 '17 05:11 NicholasLYang

@NicholasLYang Thanks! You saved me a bit of trouble. I am using recompose, and this works great:

import React from 'react'
import { compose, withHandlers, withState } from 'recompose'
import { Editor, EditorState } from 'draft-js'
import { stateToHTML } from 'draft-js-export-html'

import { Typography } from 'rmwc/Typography'

export const WidgetTextarea = ({title, editorState, onTextChange, help}) => (
  <div className='WidgetTextarea'>
    <Typography use='subtitle1'>{title}</Typography>
    <Editor editorState={editorState} onChange={onTextChange} />
    <Typography use='caption'>{help}</Typography>
  </div>
)

export default compose(
  withState('editorState', 'setEditorState', EditorState.createEmpty()),
  withHandlers({
    onTextChange: ({ onChange, setEditorState }) => e => {
      setEditorState(e)
      const fakeEvent = {target: {value: stateToHTML(e.getCurrentContent())}}
      onChange(fakeEvent)
    }
  })
)(WidgetTextarea)

onChange is an incoming prop that manages the form, based on events.

konsumer avatar May 29 '18 20:05 konsumer