draft-js-custom-styles
draft-js-custom-styles copied to clipboard
Instantiate EditorState from HTML
Hi,
Thanks for developing such a useful library!
My question might seem dumb but I can't figure how to do it... How can I generate an EditorState
out of exported HTML, which preserves inline styles?
I use the following chunk of code to get HTML from an editorState
, which works perfectly:
import { stateToHTML } from 'draft-js-export-html'
const inlineStyles = exporter(editorState)
const content = editorState.getCurrentContent()
const html = stateToHTML(content, { inlineStyles })
But then, when I do:
import { stateFromHTML } from 'draft-js-import-html'
EditorState.createWithContent(stateFromHTML("<p><span style="font-size: 34px">yo</span></p> "))
I lose the font-size
. Any hints?
Thanks a lot!
That is a good question, I don't have an answer for you right now but I will look into it and see of that would be possible. It would really be a nice to be able to import html -> draft-js and keep the styles consistent.
Thanks!
When this issue will be fixed?
@aamirbhat I am not doing any type of development with draft-js , or any draft-js library. If you would like to add an additional feature please submit a PR with tests and I will gladly take a look at it and merge it.
I have the functionality for this issue working but It depends on having a PR to draft-js-utils accepted. https://github.com/sstur/draft-js-utils/pull/155
I was able to resolve this using the draft-convert
package, here's a snippet of the code
import { convertFromHTML } from 'draft-convert';
export const convertHTMLToDraft = (htmlText: string) => {
const contentState = convertFromHTML({
htmlToStyle: (nodeName, node, currentStyle) => {
let style = currentStyle;
if (nodeName === 'span' && node.style.fontFamily) {
style = style.add(`CUSTOM_FONT_FAMILY_${node.style.fontFamily}`);
}
if (nodeName === 'span' && node.style.fontSize) {
style = style.add(`CUSTOM_FONT_SIZE_${node.style.fontSize}`);
}
return style;
},
})(htmlText);
return contentState;
};
I hope this is helpful.