react-md-editor icon indicating copy to clipboard operation
react-md-editor copied to clipboard

Header links not working under react-router

Open yusuf-kh opened this issue 3 years ago • 4 comments

Hi

The headers are currently rendered by using anchor tags. However, and as expected, these won't work if they are under a react-router path. Is there a way to replace all anchor links in the markdown with react-router's Link tag?

yusuf-kh avatar Mar 08 '22 13:03 yusuf-kh

I disabled it, did you show it?

@yusuf-kh

jaywcjlove avatar Mar 08 '22 15:03 jaywcjlove

https://github.com/uiwjs/react-markdown-preview#options-props

You need to write a rehype plugin

jaywcjlove avatar Mar 08 '22 15:03 jaywcjlove

Quick & dirty rehype plugin to restore onClick() behaviour on anchors when using react-router:

import {visit} from 'unist-util-visit';

const onNode = (node) => {
  if (node.tagName != 'a' || typeof node.properties?.href !== 'string') {
    return;
  };

  const url = node.properties.href;
  if (!url.startsWith('#')) return;

  node.properties.onClick = (e) => {
    e.preventDefault();

    // Show anchor change in address bar
    history.pushState({}, "", url);

    // Scroll to anchor
    const hash = url.replace('#', '');
    const id = decodeURIComponent(hash);
    const element = document.getElementById(id);

    if (!element) return;
    element.scrollIntoView();
  };
}

export default function rehypeAnchorOnClick() {
  return (tree) => {
    visit(tree, 'element', onNode)
  }
}

To use:

import rehypeAnchorOnClick from './rehypeAnchorOnClickPlugin';
...
      <MDEditor.Markdown 
        source={value}
        rehypePlugins={[[rehypeAnchorOnClick]]}
      />

Note: doesn't work well with rehype-sanitize, but OK with rehype-slug

strawhatgami avatar May 10 '22 23:05 strawhatgami

@strawhatgami Hello, I tried the plugin you've wrote but I have a log error telling me that Warning: Expected onClick listener to be a function, instead got a value of string type. Did you had the same error?

jMoulis avatar May 25 '23 13:05 jMoulis