Created
April 19, 2021 03:26
-
-
Save willmendesneto/0c3d7aea32e6f4342afd794e0a9be366 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from "react"; | |
import { Editor as TinyMCEEditor } from "@tinymce/tinymce-react"; | |
const defaults = { | |
init: { | |
width: "100%", | |
height: "300", | |
menubar: false, | |
branding: false, | |
plugins: ["link image", "table paste"], | |
toolbar: "undo redo | bold italic | alignleft aligncenter alignright" | |
} | |
}; | |
export const Editor = ({ onEditorChange, value, init, id, onSetupActions }) => { | |
const [configHasChanged, setRerenderEditor] = useState(false); | |
const [internalInit, setInternalInit] = useState(init); | |
const setup = editor => { | |
// Adding icons | |
if (onSetupActions.icons) { | |
onSetupActions.icons.forEach(item => { | |
editor.ui.registry.addIcon(item.name, item.icon); | |
}); | |
} | |
// Adding toggle buttons | |
if (onSetupActions.togleButtons) { | |
onSetupActions.togleButtons.forEach(item => { | |
editor.ui.registry.addToggleButton(item.name, { | |
icon: item.icon, | |
tooltip: item.tooltip, | |
onAction: item.onAction | |
}); | |
}); | |
} | |
}; | |
// Unfortunately, the easiest way to make sure the editor will be updated and respect React lifecycle | |
// is by forcing a remount in case of configuration changes. | |
// Since this won't happen that often, it shouldn't be a problem in your app | |
const forceEditorRerender = () => { | |
setRerenderEditor(true); | |
requestAnimationFrame(() => setRerenderEditor(false)); | |
}; | |
useEffect(() => { | |
if (JSON.stringify(init) !== JSON.stringify(internalInit)) { | |
setInternalInit(init); | |
forceEditorRerender(); | |
} | |
}, [init]); | |
return configHasChanged ? null : ( | |
<TinyMCEEditor | |
id={id} | |
init={{ | |
...defaults.init, | |
...internalInit, | |
id, | |
setup, | |
}} | |
value={value} | |
onEditorChange={onEditorChange} | |
/> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment