react-markdown:
cannot appear as a descendant of

.

I am setting imageReference in renderers wich wrap img with div and I got this error

const imageRenderer = ({src, alt}) => {
  return (
    <div className="markdown-image__wrapper">
      <img src={src} alt={alt || ''}/>
    </div>
  )
}

const renderers = {imageReference: imageRenderer}
const md = <ReactMarkdown source={value}renderers={renderers}/>

error:

Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>.
    in div (at ...)
    in imageRenderer (created by ReactMarkdown)
    in p (created by ReactMarkdown)
    in div (created by ReactMarkdown)

how I can fix this?

Note: It render correctly, but error shown in console

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 16
  • Comments: 23 (16 by maintainers)

Most upvoted comments

I would really like to know that to if someone finds the solution…

I used something like this to fix img-tags from being wrapped in p-tags:

const ParagraphRenderer = ({ children }) => {
  const hasImage = !!children.find(
    (child) => typeof child === 'object' && child.key && !!child.key.match(/image/g)
  )
  return hasImage ? children : <p>{children}</p>
}

@EKMN and @yassinebridi code didn’t work for me.

Here is how I removed <p> tags around images:

const imagesWithoutPTags = (props) => {
  const element = props.children[0];
  return element.type === 'img' ? { ...element } : <p {...props} />;
};

<ReactMarkdown
  source={source}
  escapeHtml={false}
  renderers={{paragraph: imagesWithoutPTags}}
/>

@wooorm The new version breaks any solution on this issue and it reopens the problem, is there any solution for this issue with the new version?

@wooorm Thanks, it is great.

Markdown does not allow images outside of paragraphs/headings, so you can’t just add a div there.

You can unwrap them though, e.g., with https://github.com/remarkjs/remark-unwrap-images. Or you can make your own plugin.

The issue happens because you can’t have div inside of a paragraph. So You may write:

<ReactMarkdown source={yourContent} renderers={{ paragraph: props => <div {...props} />, }} />

Now, the paragraph becomes a div, and there is no more troubles 😉.