hashicorp / next-mdx-remote

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

Different name of children type for image #293

Closed hendraaagil closed 1 year ago

hendraaagil commented 2 years ago

I have a markdown like this to display an image:

![Project View](/assets/blog/berkenalan-dengan-react-memahami-useeffect/project-view.png)

I want to wrap that image using figure element. So, in Paragraph component I add condition like this:

  if (children.type && children.type.name === 'Image') {
    return (
      <Box
        as="figure"
        my={3}
        mx="auto"
        w="fit-content"
        bg={bgColor}
        textAlign="center"
        rounded="md"
        overflow="hidden"
      >
        {children}
      </Box>
    );
  }

  return (
    <Text my={3} fontWeight="400">
      {children}
    </Text>
  );

In development server, it rendered correctly image

But, after I build and start the (production) server. It rendered p instead of figure element image

After that, I find that children.type.name value can be either 'H' or 'P' when I start in production server. So, my solution is adding a condition like this 😅

  if (
    children.type &&
    (children.type.name === 'Image' ||
      children.type.name === 'P' ||
      children.type.name === 'H')
  ) {
    ...
  }

But, anyone know how this can happen? Because it confused me.

"next-mdx-remote": "^4.1.0"

Thanks.

timomeh commented 1 year ago

Instead of unwrapping the image from the paragraph yourself, you can use the https://github.com/remarkjs/remark-unwrap-images plugin. It removes the wrapping paragraph.

import remarkUnwrapImages from 'remark-unwrap-images'

<MDXRemote
  options={{
    mdxOptions: {
      remarkPlugins: [
        remarkUnwrapImages,
      ]
    }
  }}
/>
hendraaagil commented 1 year ago

Thanks @timomeh! That plugin works perfectly for me.