1

This is a question on how to deal with pasted image using draftjs in the case of Japanese input mode.

Recently I am using Draft.js as text editor. Sometimes we need to insert image into the editor like copy image and paste the image into the editor area.

Everything goes well but the strange thing happens when I try to input Japanese words together with pasted image.

Input Japanes and press "Enter" key As the image above, After inputing Japanese words, I pressed "Enter" key to confirm the Japanese words. But after I pressed "Enter" Key, the following Errors happens. Error after pressed "Enter"

I think the problem is cased by the Japanese Input dialog destroyed the entity key of Draft.js

Could someone give me some hint on how to solve the problem?

My code is the following.

import React, {useState} from 'react';
import './App.css';
import {Editor, EditorState, convertFromRaw, ContentBlock} from 'draft-js';

function App() {
  const initData = convertFromRaw({
    blocks: [
      {
        key: "98pea",
        text: "https://dummyimage.com/100x100/000/fff",
        type: "atomic",
        depth: 0,
        inlineStyleRanges: [],
        entityRanges: [
          {
            offset: 0,
            length: 1,
            key: 0,
          },
        ],
        data: {},
      },
      {
        key: "16d04",
        text: "testtest。",
        type: "unstyled",
        depth: 0,
        inlineStyleRanges: [],
        entityRanges: [],
        data: {},
      },
    ],
    entityMap: {
      0: {
        type: "image",
        mutability: "IMMUTABLE",
        data: { src: "https://dummyimage.com/100x100/000/fff" },
      },
    },
  });

  const initState = EditorState.createWithContent(initData)
  const [editorState,setEditorState] = useState(initState)

  const Image = (props:any) => {
    return <img src={props.src} alt="" />;
  };

  const Media = (props:any) => {
    const entity = props.contentState.getEntity(props.block.getEntityAt(0));
    const { src } = entity.getData();

    const type = entity.getType();

    let media;
    if (type === "image") {
      media = <Image src={src} />;
    }

    return media;
  };

  const myBlockRenderer = (block:ContentBlock) => {
    if (block.getType() === "atomic") {
      return {
        component: Media,
        editable: false,
      };
    }
    return null
  }

  return (
    <div className="App">
      <div>
        <Editor editorState={editorState} onChange={setEditorState} blockRendererFn={myBlockRenderer} />
      </div>
    </div>
  );
}

export default App;

Zhongwei Xu
  • 147
  • 9

0 Answers0