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'
import './customEditor.scss'
interface CustomEditorProps {
baseState: EditorState
editorType: 'info' | 'title' | 'content' | 'question' | 'link' | 'subject'
handleChange: (
value: string,
type: 'info' | 'title' | 'content' | 'question' | 'link' | 'subject'
) => void
}
const CustomEditor: React.FC<CustomEditorProps> = ({
baseState,
handleChange,
editorType,
}: CustomEditorProps) => {
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)
handleChange(htmlState, editorType)
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