Custom component in react-markdown content

Published on

Say I want to implement a pop-over using shadcn in a markdown text in react. I convert the markdown to HTML to display it. But how to inject my own component into that output? Turns out react-markdown already handles it by giving me the ability to pass in my own components for parts of markdown.

const md = `
# The Rise of TypeScript

TypeScript achieves its popularity by combining several powerful features designed for robust and scalable application development.

A key factor [1](#1) is its unique static typing system layered on top of standard JavaScript.
In a **Developer Survey**, TypeScript was ranked the second most loved language by professional developers [163].
`

export function Playground() {

    return <div>
        <Markdown
            components={{
                "a": LinkInMarkdown,
            }}
        >{md}</Markdown>
    </div>
}

export function LinkInMarkdown({ children, ...props }: any) {
    console.log("LinkInMarkdown", props);
    return <a href={props.href} className="text-blue-500 hover:underline">[{children}]</a>
}

Best would be to detect things like [163] but this is not a component. Thus, I converted the [1] to [1](#1). I can then detect a pattern in LinkInMarkdown and return something else (not implemented.)

Tags: