Newer
Older
import { convertToRaw } from 'draft-js'
import draftToHtml from 'draftjs-to-html'
import React, { useCallback, useState } from 'react'
import { Editor, EditorState } from 'react-draft-wysiwyg'
export type EditorType =
| 'info'
| 'title'
| 'content'
| 'question'
| 'link'
| 'subject'
| 'image'
| 'custom_popup'
interface CustomEditorProps {
baseState: EditorState
type: EditorType
handleChange: (value: string, type: EditorType) => void
}
const CustomEditor: React.FC<CustomEditorProps> = ({
baseState,
handleChange,
const [editorState, setEditorState] = useState<EditorState>(baseState)
const convertStateToHTML = (state: EditorState) => {
const parseElements = ({ type, data }: { type: string; data: any }) => {
// properly align images (see: https://github.com/jpuri/draftjs-to-html/issues/28#issuecomment-607344551)
if (type === 'IMAGE') {
const alignment = data.alignment || 'none'
const textAlign = alignment === 'none' ? 'center' : alignment
const alt = data.alt ? data.alt : ''
return `<p style="text-align:${textAlign};"><img src="${data.src}" alt="${alt}" style="height: ${data.height};width: ${data.width}"/></p>`
}
return state.getCurrentContent().hasText()
? draftToHtml(
convertToRaw(state.getCurrentContent()),
{},
false,
parseElements
)
: ''
}
const handleStateChange = useCallback(
(state: EditorState) => {
setEditorState(state)
const htmlState = convertStateToHTML(state)
return (
<Editor
editorState={editorState}
onEditorStateChange={(state) => handleStateChange(state)}
handlePastedText={() => false}
wrapperClassName="wrapper-class"
editorClassName="editor-class"
toolbarClassName="toolbar-class"
toolbarCustomButtons={[
<CustomLink key="customLink" editorState={editorState} />,
]}
/>
)
}
export default CustomEditor