hashicorp / next-mdx-remote

Load MDX content from anywhere
Mozilla Public License 2.0
2.68k stars 140 forks source link

<figure> cannot appear as a descendant of <p>. #414

Closed piscopancer closed 11 months ago

piscopancer commented 11 months ago

This happens because an figure (image + below text) are rendered inside a p tag. But how do I explain MDXRemote that this component rather not be contained in a p tag but be a standalone block element?

Look at that image

That's the code btw

<MDXRemote
  source={article.text} // markdown text, all good
  components={{
    // ...
    img: ({ src, alt }) => {
      return (
        <figure>
          <img src={src} alt={alt} />
          <figcaption>{alt}</figcaption>
        </figure>
      )
    }
  }}
/>

Please help 😉💋

stern-shawn commented 11 months ago

Take a look at a remark plugin such as remark-unwrap-images which will automatically remove the unwanted, wrapping p tag. This has also been a bane of my existence in a project 😅

Be sure to pass the plugin as part of your serialize config, for example:

serialize(
  yourMdxString, // Raw MDX input here
  {
    mdxOptions: {
      remarkPlugins: [
        remarkUnwrapImages,  // where the magic happens ✨
        ... // other plugins you're using
      ],
      rehypePlugins: [],
      format: 'mdx',
    },
    ...
  }
)
piscopancer commented 11 months ago

@stern-shawn ✅ It's working. I use next-mdx-remote to process strings as MDX and that's the only thing I did

import { MDXRemote } from 'next-mdx-remote/rsc'

// ...

<MDXRemote
  source={article.text}
  options={{
    mdxOptions: {
      remarkPlugins: [remarkUnwrapImages],
    },
  }}
/>

And there is actually no more p strangling an image 🤯

image