1

I'm making a markdown editor with viewer (side by side).

I'm facing a problem where typing the syntax for image in markdown will cause a

Unhandled Runtime Error
Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {"width":600,"height":300}

typing ![]() the boilerplate code for inserting markdown image causes the error to happen. Anyone knows a way to handle this?

This is my code

import { FC } from "react";
import Image from "next/image";
import ReactMarkdown, { } from "react-markdown";

interface Props {
  props: string
}

const Markdown:FC<Props> = ({props}) => {
  const MarkdownComponents: Object = {
    p: (paragraph: any) => {
      const { node } = paragraph;

      if (node.children[0].tagName === "img") {
        try {
          const image = node.children[0];
          const alt = image.properties.alt?.replace(/ *\{[^)]*\} */g, "");
          const isPriority = image.properties.alt?.toLowerCase().includes('{priority}');
          const metaWidth = image.properties.alt.match(/s{([^}]+)x/);
          const metaHeight = image.properties.alt.match(/x([^}]+)}/);
          const width = 600// metaWidth ? metaWidth[1] : "600";
          const height = 300//metaHeight ? metaHeight[1] : "300";
          

          return (
            <Image
              src={image.properties.src}
              width={width}
              height={height}
              className="postImg"
              alt={alt}
              priority={isPriority}
              layout="responsive"
            />
          )
        } catch (error) {
          console.log(error)
        }
      }
      return <p>{paragraph.children}</p>
    }
  }

  return (
    <ReactMarkdown 
      className="prose"
      components={MarkdownComponents}
    >
      {props}  
    </ReactMarkdown>
  )

}

export default Markdown;
jasjamjos
  • 79
  • 6

1 Answers1

1

Nevermind, just added conditional return for <Image /> to check if image.properties.src exists:

if (image.properties.src) return (
  <Image ...props />
)

I dont know if this is the best or optimal solution tho, but it works for me

jasjamjos
  • 79
  • 6