Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Header links not working under react-router #356

Open
yusuf-kh opened this issue Mar 8, 2022 · 4 comments
Open

Header links not working under react-router #356

yusuf-kh opened this issue Mar 8, 2022 · 4 comments

Comments

@yusuf-kh
Copy link

yusuf-kh commented Mar 8, 2022

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 yusuf-kh changed the title Header links not working Header links not working under react-router Mar 8, 2022
@jaywcjlove
Copy link
Member

I disabled it, did you show it?

@yusuf-kh

@jaywcjlove
Copy link
Member

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

You need to write a rehype plugin

@strawhatgami
Copy link

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

@jMoulis
Copy link

jMoulis commented May 25, 2023

@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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants