I am using draft-js to create my own editor. I am using convertToRaw and convertFromRaw methods to store and retrieve the edited text from the database. While convertToRaw method is working fine. The convertFromRaw method is missing out the fontSize and fontFamily styles being applied to the edited text. But the inline styles like ‘Bold’ are correctly displayed.
I am using the getCustomStyleMap() from draftjs-utils library for customStyleMap attribute of the draft-js Editor. I am not sure, if that is causing the convertFromRaw method to function incorrectly.
Any thoughts on this would be highly helpful.
Below is my soure code.
const App = () => {
const [editorState, setEditorState] = useState(
() => EditorState.createEmpty()
);
const [item, setItem] = useState('');
const textRef = useRef(null);
const updateEditorState = (state) => {
setEditorState(state);
const val = JSON.stringify(convertToRaw(state.getCurrentContent()));
console.log(val);
setItem(val);
localStorage.setItem('string', item);
}
useEffect(() => {
const val = localStorage.getItem('string');
console.log(val);
const formatted = convertFromRaw(JSON.parse(val));
setEditorState(EditorState.createWithContent(formatted));
}, [])
const onFontSizeChange = (e) => {
const newState = toggleCustomInlineStyle(editorState, 'fontSize', e.target.value);
updateEditorState(newState);
}
const onFontFamilyChange = (e) => {
const newState = toggleCustomInlineStyle(editorState, 'fontFamily', e.target.value);
updateEditorState(newState);
}
const onClick = (e) => {
e.preventDefault();
const newEditorState = RichUtils.toggleInlineStyle(editorState, 'BOLD');
setEditorState(newEditorState);
}
const focusEditor = () => {
textRef.current.focus();
}
const onDrop = (event) => {
event.stopPropagation();
}
return (
<div>
<div className="toolbar">
<select onChange={onFontSizeChange} onClick={onDrop} className="selectbox">
<option value="10px">10px</option>
<option value="20px">20px</option>
<option value="30px">30px</option>
<option value="40px">40px</option>
<option value="50px">50px</option>
<option value="60px">60px</option>
<option value="70px">70px</option>
</select>
<select onChange={onFontFamilyChange} className="selectbox">
<option value="Times New Roman">Times New Roman</option>
<option value="fantasy">Fantasy</option>
<option value="Georgia">Georgia</option>
<option value="Courier New">Courier New</option>
<option value="cursive">Cursive</option>
</select>
<button className="selectbox" onMouseDown={onClick}>Bold</button>
</div>
<div className="editbox" onClick={focusEditor}>
<Editor
ref={textRef}
customStyleMap={getCustomStyleMap()}
editorState={editorState}
onChange={updateEditorState}
/>
</div>
</div>
)
}