draft-js-utils
draft-js-utils copied to clipboard
Uncaught TypeError: this.contentState.getBlocksAsArray is not a function
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
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 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.