TJ Gillis
TJ Gillis

Reputation: 507

Rehype to render hashtag as url

Trying to make a something like #tag render as a URL the markdown editor MDEditor using rehypeRewrite. Here's what I have so far

const REG = /\B(\#[a-zA-Z]+\b)(?!;)/gi;

<MDEditor 
    style={{width: "100%", height: "100%"}} 
    minHeight={500} 
    value={value} 
    onChange={(event) => {
        setValue(event || '');
    }} 
    previewOptions={{
        rehypePlugins: [
            [
            rehypeRewrite,
            {
                rewrite: (node : any, index: any, parent: any) => {
                if (node.type === "element" && node.tagName === "p") {
                    let text = getCodeString(node.children);
                    if (REG.test(text)) {
                        node.children = [
                        {
                            type: 'link',
                            url: 'https://example.com',
                            children: [{type: 'text', value: text} ]
                        }];
                    }
                }}
            },
        ]],
    }}
/>

The regex properly matches the text but instead of the node being replaced with a link, it just doesn't render anything.

Any guidance on what I may be doing wrong would be much appreciated

Upvotes: 1

Views: 90

Answers (1)

Damzaky
Damzaky

Reputation: 10824

The regex you provided seems correct, the mistake here is how you make the link element. Instead of type link, you should still use type element, and for a link, you need to add additional tags, such as tagName: "a" and properties: {href: 'https://example.com'}.

Basically you can replace the node.children code with this:

                      node.children = [
                        {
                          type: "element",
                          tagName: "a",
                          properties: {
                            href: "https://example.com",
                          },
                          children: [{ type: "text", value: text }],
                        },
                      ];

Upvotes: 1

Related Questions