'Trying to set default font size in DraftJS editor

I am trying to implement font-size changing feature in DraftJS. I have got it working to the point that clicking on specific font-size buttons causes the editor to begin applying that font-size. However, I want to set a default font-size that is captured by Draft as a starting inline style (think of it like applying the BOLD or ITALIC built-in inline style as soon as the editor is rendered the first time, but with my custom inline style).

I am using useEffect() to set that default inline style:

const [editorState, setEditorState] = useState(() =>
    EditorState.createEmpty()
);

const onChange = (nextEditorState) => {
    setEditorState(nextEditorState);
}

useEffect(() => {
    editorRef.current.focus();

    // set inline style to current selection, which is a collapsed selection

    onChange(nextEditorState);
}, []);

This wasn't working, and I was confused since I used that same font-size application logic in the buttons that toggle them. So I used the getInlineStyleOverride() method on editorState to see if it was being applied correctly:

const onChange = (nextEditorState) => {
    // this one checks if the new to-be-applied editor state actually
    // has inlineStyleOverride applied, and it logs a DraftInlineStyle
    // object that shows that it does
    console.log(nextEditorState.getInlineStyleOverride());

    setEditorState(nextEditorState);

    // this one checks if it was applied to the editorState. this shows
    // there is no inlineStyleOverride (logs null instead of 
    // a DraftInlineStyle)
    console.log(editorState.getInlineStyleOverride());
}

So, I am trying to set the editorState so that the current collapsed selection has an inline style applied to it. It even shows that nextEditorState has a inlineStyleOverride. However, after using setEditorState, editorState doesn't have that inlineStyleOverride applied to it.

How can I fix this issue?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source