Search code examples
reactjstypescriptvitemarkdoc

How to use Markdoc in React + TypeScript + Vite app


Document.tsx

import React from "react";
import Markdoc from "@markdoc/markdoc";

const config = {};

interface DocumentProps {
    source: string;
}

export function Document({ source }: DocumentProps) {
    const ast = Markdoc.parse(source);
    const content = Markdoc.transform(ast, config);

    return Markdoc.renderers.react(content, React);
}

export default Document;

Home.tsx

import { Document } from "@containers";

export function Home() {
    return (
        <div>
            <Document
                source={`
                    # Hello world.
                    > My first Markdoc page
                `}
            />
        </div>
    );
}

export default Home;

I wanna see markdown but it's being rendered as a normal text # Hello world. > My first Markdoc page.

There were some tutorials and guides for Next.js + Markdoc app, but they all didn't work for my app.


Solution

  • Markdown is sensitive for indentation and your source has incorrect indentation. It's also recommended to separate headings, paragraph quotes etc. with a empty line.

    import { Document } from "@containers";
    
    export function Home() {
      return (
        <div>
          <Document
            source={`# Hello world.
    
    > My first Markdoc page`}
          />
        </div>
      );
    }
    
    export default Home;