Image insertion at cursor in editor using slatejs

4.6k Views Asked by At

I am trying to implement a Rich Text editor using reactjs and slate.js. So far, i was able to get most features working, however unable to add images to the document at the cursor is not working (Image insertion at beginning of the document is working, however).

when iam trying to insert it any other point iam getting the error. at the renderpart i.e., executing the onchange method of the editor.

    const target = getEventRange(e, this.state.EditorComp.state.value)
change = this.state.EditorComp.state.value.change().call(this.insertImage, filelocation,target)
this.state.EditorComp.onChange(change);

slate-react.es.js:1229 Uncaught Error: Unable to find a DOM node for "51". This is often because of forgetting to add `props.attributes` to a custom component.
at findDOMNode$1 (slate-react.es.js:1229)
at findDOMPoint (slate-react.es.js:1247)
at findDOMRange (slate-react.es.js:1290)

My code is based on the link https://github.com/ianstormtaylor/slate/blob/master/examples/images/index.js

Please help.

2

There are 2 best solutions below

0
On

Do you have a schema defined for your editor? I had this same error until I added a schema for images that set isVoid to true. You need at least the following in your schema:

const schema = {
  blocks: {
    image: {
      isVoid: true
    }
  }
};
0
On

I would imagine you would want to insert the image inline if you want it at the cursor:

change.insertInline({
  type: 'img',
  isVoid: true,
  data: { location: location }
})
change.moveToStartOfNextText().focus()

Then in your renderNode method:

const { attributes, node, isSelected } = props
if (node.type === 'img') { 
  node.data.get('location')
  return <img ... />
}