1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

draft-js draftjs-to-htmlを使って、HTMLからフォントカラーを復元したテキストを表示する

Last updated at Posted at 2022-02-11

はじめに

convertFromHTMLでは一部のインラインスタイルにしか対応しておらず、フォントカラーが復元されないという問題があります。
html-to-draftjsがフォントカラーなどのInlineStylesの復元に対応しているので軽く使ってみようと思います。

行程は以下の通りです。

  1. htmlToDraftを使ってhtmlを変換し、editorStateを作成する
  2. color-〇〇の名前でInlineStyleを作成、styleMapに追加する
  3. 1と2で作成したeditorStateとstyleMapをEditorにセットする

1.htmlToDraftを使ってhtmlを変換し、editorStateを作成する

const html = `<span style="color:rgb(0,128,0)">te</span><span style="color:red">st</span>`;

const htmlToEState = (html:string) =>{

    const blockArray = htmlToDraft(html);
    const contentState = ContentState.createFromBlockArray(blockArray.contentBlocks, blockArray.entityMap);
    const editorState = EditorState.createWithContent(contentState);

    return editorState;
}

2.color-〇〇の名前でInlineStyleを作成、styleMapに追加する

htmlToDraftでは'color-'とhtmlElementのcolorにある値を結合して、InlineStyleをセットします。colorには'red'で値がはいるので'color-Red'と定義したら色が変わらなくなるので注意してください。rgbでの定義にも対応しています。

const styleMap = {
    'color-red':{ 'color':'red'},
    'color-rgb(0,128,0)':{ 'color':'rgb(0,128,0)'}
}

3. 1と2で作成したeditorStateとstyleMapをEditorにセットする


const RichTextEditor = () => {
    const [ editorState, setEditorState ] = useState(htmlToEState(html));

    return(
        <Editor customStyleMap={styleMap} editorState={editorState} onChange={setEditorState}/>
    );
}

テキストの表示

下図のように表示されました。
image.png

最後に

htmltodraftでは背景色、フォントサイズ、フォントファミリーにも対応しているので使ってみてください。
InlineStyle名はそれぞれ、bgcolor-〇〇、fontsize-〇〇(例:smallもしくは12)、fontfamily-(例: MS PGothic)

styleMap例

const styleMap = {
    'fontfamily-MS Mincho':{ 'fontFamily':'MS Mincho'},
    'bgcolor-red':{ 'backgroundColor':'red'},
    'fontsize-32':{'fontSize':'32px'}
}

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?