Created
March 4, 2016 18:01
-
-
Save ditlevtojner/17d65e9884d688eb383d to your computer and use it in GitHub Desktop.
How to create a draft.js "viewer"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ty