draft-convert: Using convertToHTML returning an tag in blockToHTML gives error

I get the following error when I try to use draft-convert convertToHTML returning an <img> tag in blockToHTML gives error

Uncaught Error: img is a void element tag and must neither have 'children' nor use 'dangerouslySetInnerHTML'

Here is my function for exporting to html.

export function editorStateToHtml (editorState) {
  if (editorState) {
    const html = convertToHTML({
      styleToHTML: (style) => {
        if (style === 'BOLD') {
          return <span style={{color: 'blue'}} />;
        }
      },
      blockToHTML: (block) => {
        const type = block.type
        if (type === 'atomic') {
          let url = block.data.src
          return <img src={url} />
        }
        if (type === 'unstyled') {
          return <p />
        }
      },
      entityToHTML: (entity, originalText) => {
        if (entity.type === 'LINK') {
          return <a href={entity.data.url}>{originalText}</a>;
        }
        return originalText;
      }
    })(editorState.getCurrentContent());

    return html
  }
}

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 1
  • Comments: 17 (5 by maintainers)

Most upvoted comments

i know its too late but i’m just trying to help those who have this issue in the future. just have this issue today for showing <img> tag and im using ‘entityToHTML’ and its fix the problem for me.

const currentContentAsHTML = convertToHTML({
      entityToHTML: (entity, originalText) => {
        if (entity.type === 'IMAGE') {          
          return `<img src="${entity.data.src}" />`;
        }
        return originalText;
      },
    })(editorState.getCurrentContent());

Actually the following worked fine though using start and end and returning a string. So that is an option for anyone experiencing this issue.

      blockToHTML: (block) => {
        const type = block.type
        if (type === 'atomic') {
          let url = block.data.src
          return { start: "<img src='" + (url) + "'", end: "</img>" }
        }
        if (type === 'unstyled') {
          return <p />
        }
      },

@wulucxy I exported blocks of the content state using getBlockMap , then I looped on each block and if the block is of the corresponding entity then I replace its text by an empty string ''. Then I transformed those blocks back into content state using createFromBlockArray (sorry I don’t have the exact code with me, I no longer work on the project I used this on)