Skip to content
Snippets Groups Projects
CustomEditor.tsx 2.12 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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'
    
    Bastien DUMONT's avatar
    Bastien DUMONT committed
    import CustomLink from './CustomLink'
    
    
    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)
    
        [editorType, handleChange]
    
    
      return (
        <Editor
          editorState={editorState}
          onEditorStateChange={(state) => handleStateChange(state)}
    
          handlePastedText={() => false}
    
          wrapperClassName="wrapper-class"
          editorClassName="editor-class"
          toolbarClassName="toolbar-class"
    
    Guilhem CARRON's avatar
    Guilhem CARRON committed
          toolbarCustomButtons={[
            <CustomLink key="customLink" editorState={editorState} />,
          ]}
    
        />
      )
    }
    export default CustomEditor