brohlson / gatsby-plugin-anchor-links

⚓ Gatsby plugin for using smooth scroll anchor links with a Gatsby Link component
https://www.npmjs.com/package/gatsby-plugin-anchor-links
MIT License
68 stars 22 forks source link

Anchor the element in the same page not working. #47

Open aruiplex opened 1 year ago

aruiplex commented 1 year ago

Hi there.

I would like to use the table of content to anchor the elements in the mdx, which in the same page, but it doesn't work.

I use the gatsby file system to generate pages by the mdx files.

This is the Layout of the mdx template to add the AnchorLink to the h1 tags.

import React from "react";
import { MDXProvider } from "@mdx-js/react";
import { AnchorLink } from "gatsby-plugin-anchor-links";

const MyH1 = (props) => {
  return (
    <h1>
      <AnchorLink to={"#" + props.children}>{props.children}</AnchorLink>
      {/* <a href={"#" + props.children}>{props.children}</a> */}
    </h1>
  );
};

const components = {
  h1: MyH1,
};

export default function Layout({ children }) {
  return <MDXProvider components={components}>{children}</MDXProvider>;
}

And this is a part of my code to generate table of content :

 export const MyToc = ({ url, title, items, level = 0 }) => {
  const hasChildren = items && items.length;

  return (
    <div>
      <AnchorLink to={url} style={{ paddingLeft: level * 20 + "px" }}>
        {title}
      </AnchorLink>

      {hasChildren &&
        items.map((item) => (
          <MyToc key={item.title + item.url} {...item} level={level + 1} />
        ))}
    </div>
  );
};

However, it cannot jump to the element which is in the same page. If I click the anchor element, the URL in the browser will like this: http://localhost:8000/contents/alexnet/#Alexnet. It is the page URL: http://localhost:8000/contents/alexnet/. The hash tag cannot attach behind the page without /.

Thank you for your loveable work.

AndreaCorda01 commented 1 year ago

I have the same problem. Seems a incompatibily with the routing system provided by React and Gatsby. But I haven't achieved to get more information regarding the issue.

AndreaCorda01 commented 1 year ago

I have just solved the problem and it was that the react component was not receiving correct the id="mission" tag and once I have updated the component, it worked 🥳