Improve usage docs - Handle HTML data
vousys opened this issue · comments
Hi! I love your customization of draft-js. Maybe you could improve usage docs with this information, many newbie devs will be pleased.
Load default HTML data to the editor, save data content to HTML and JSON
import React from 'react'
// UTILS: get from: https://github.com/sstur/draft-js-utils
import { stateToHTML } from 'draft-js-export-html'
import { stateFromHTML } from 'draft-js-import-html'
// Megadraft: get from https://megadraft.io/
import {
MegadraftEditor,
editorStateFromRaw,
editorStateToJSON,
DraftJS,
} from 'megadraft'
import 'megadraft/dist/css/megadraft.css'
export default function WYSWYG(props) {
// Get default HTML data from your DB
const {value} = props
// handle editor state. Set default html value
const [editorState, setEditorState] = React.useState(() =>
value === null
? editorStateFromRaw(value)
: DraftJS.EditorState.createWithContent(DraftJS.convertFromHTML(value)),
)
// Convert data content to JSON
const convert_editor_content_to_JSON = () => {
console.log( 'convert_editor_content_to_JSON : ', editorStateToJSON(editorState) )
}
// Convert data content to HTML
const convert_editor_content_to_HTML = () => {
console.log( 'convert_editor_content_to_HTML : ', stateToHTML(editorState.getCurrentContent() ) )
}
return (
<>
<div style={{ marginLeft: 80 }}>
<MegadraftEditor
ref={editor}
editorState={editorState}
onChange={setEditorState}
placeholder="Write something!"
/>
<a href="#" onClick={convert_editor_content_to_HTML}>Convert to HTML</a>
{' | '}
<a href="#" onClick={convert_editor_content_to_JSON}>Convert to JSON</a>
</div>
</>
)
}
Hi, @vousys!
Glad you loved it! Thanks!
About the docs request:
There's a section that covers the conversion from EditorState
to JSON
. The example is very similar to the one you suggested.
About loading the EditorState
from an HTML
string, we could add some docs since this is supported by Draft.js. Or link to Draft.js docs for that feature. It may have some caveats concerning Custom Blocks and Entities though.
Exporting the EditorState
to HTML
it's not in the scope of this project. For that you really should write your own exporter or use some lib as you did in the example above. In conclusion, we opted not to include HTML
export in the docs. At most, we could link to some 3rd party libs that do that job.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.