Skip to content

Instantly share code, notes, and snippets.

@ditlevtojner
Created March 4, 2016 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ditlevtojner/17d65e9884d688eb383d to your computer and use it in GitHub Desktop.
Save ditlevtojner/17d65e9884d688eb383d to your computer and use it in GitHub Desktop.
How to create a draft.js "viewer"
/*
Draft.js came out, thank you again Facebook, Easy to implement,
but i struggled with how it could work with persisting it backend and then parseing it.
The flow looks like this
1. DraftJsEditor has set state with an immutable-js obj contaning the state of the contentfield
2. we transform it to json via:
*/
let data = {
content: JSON.stringify(convertToRaw(this.state.content.getCurrentContent()))
}
/*
3. data has been persisted backend, and we recieve a json encoded object in return.
*/
import React from 'react'
import {Editor, convertFromRaw, ContentState, EditorState} from 'draft-js'
import Type from 'typeHelpers'
function isDraftable(content) {
return Type(content, 'object') && content.hasOwnProperty('entityMap')
}
export default class DraftViewer extends React.Component {
constructor(props) {
super(props)
}
render() {
let content = this.props.children
// legacy; might be a string, not object
try {
content = JSON.parse(content)
}
catch(e) {}
if (isDraftable(content)) {
content = EditorState.createWithContent(
ContentState.createFromBlockArray(
convertFromRaw(content)))
return <Editor readOnly={true} editorState={content} />
}
return <p>{content}</p>
}
}
@smrazvan
Copy link

ty

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment