Skip to content

Instantly share code, notes, and snippets.

@paul-phan
Last active December 10, 2021 11:57
Show Gist options
  • Save paul-phan/209da7721a279465aff39d97fdbf988d to your computer and use it in GitHub Desktop.
Save paul-phan/209da7721a279465aff39d97fdbf988d to your computer and use it in GitHub Desktop.
React 16.4 controlled input sync with react-draft-wysiwyg => changed using lifting state up.
import React from 'react'
import { Editor as DraftEditor } from 'react-draft-wysiwyg'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import { ContentState, convertToRaw, EditorState } from 'draft-js'
import draftToHtml from 'draftjs-to-html'
import htmlToDraft from 'html-to-draftjs'
import PropTypes from 'prop-types'
class Editor extends React.Component {
static propTypes = {
editorState: PropTypes.instanceOf(EditorState),
onEditorStateChange: PropTypes.func
}
render() {
return (
<DraftEditor
editorState={this.props.editorState}
onEditorStateChange={this.props.onEditorStateChange}
/>
)
}
}
export default class App extends React.Component {
state = {
value: 'Hello world!',
editorState: App.generateEditorStateFromValue('Hello world!'),
}
onEditorStateChange = editorState => {
this.setState(
{
editorState,
value: draftToHtml(
convertToRaw(editorState.getCurrentContent())
)
}
)
}
static generateEditorStateFromValue(value) {
const contentBlock = htmlToDraft(value || '')
const contentState = ContentState.createFromBlockArray(
contentBlock.contentBlocks
)
return EditorState.createWithContent(contentState)
}
updateValue = value => this.setState({ value, editorState: App.generateEditorStateFromValue(value) })
render() {
return (
<div>
<input value={this.state.value} onChange={e => this.updateValue(e.target.value)} />
<div><Editor editorState={this.state.editorState} onEditorStateChange={this.onEditorStateChange} /></div>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment