kentcdodds / mdx-bundler

🦤 Give me MDX/TSX strings and I'll give you back a component you can render. Supports imports!
MIT License
1.79k stars 75 forks source link

Hash navigation not working in Next.js #44

Closed MatthewCaseres closed 3 years ago

MatthewCaseres commented 3 years ago

Relevant code or config

import { bundleMDX } from "mdx-bundler";
import {getMDXComponent} from 'mdx-bundler/client'
import {useMemo} from 'react'
import path from 'path'

if (process.platform === 'win32') {
  process.env.ESBUILD_BINARY_PATH = path.join(
    process.cwd(),
    'node_modules',
    'esbuild',
    'esbuild.exe',
  )
} else {
  process.env.ESBUILD_BINARY_PATH = path.join(
    process.cwd(),
    'node_modules',
    'esbuild',
    'bin',
    'esbuild',
  )
}

export const getStaticProps = async ({ params }) => {
  const mdxSource = `

${Array(1000).fill(0).map((_, index) => {
  return `<h2 id="${index}">${index}</h2>`
})}

`.trim();

  const result = await bundleMDX(mdxSource);

  const { code } = result;
  return {
    props: { code }, // will be passed to the page component as props
  };
};

export default function Post({ code }) {
  const Component = useMemo(
    () => getMDXComponent(code))
  return (
    <div>
      <Component />
    </div>
  );
}

Hash links don't work in Next.js on refresh. If you navigate to them while on the page it will work but if you go to them directly you can get problems.

The screen goes down to the hash link but then goes up again.

next hash

Reproduction repository:

https://github.com/MatthewCaseres/mdx-bundler-experiments

Notes: This is an issue in next-mdx-remote as well, here's an issue that is related but not identical from their repo. https://github.com/hashicorp/next-mdx-remote/issues/65

Arcath commented 3 years ago

I don't belive linking to the id of a h2 is valid.

Can you confirm that the id attribute in appearing on the h2 tags?

MatthewCaseres commented 3 years ago

Yeah it's on there.

Arcath commented 3 years ago

That code is working on my machine in Firefox, Chrome and Edge.

If the id's are making it into the DOM it should be working no problem, mdx-bundler has outputted the correct HTML.

MatthewCaseres commented 3 years ago

Hmm, it happens consistently for me in local development but not when I deployed to https://mdx-bundler-experiments.vercel.app.

Thanks for your responsiveness and maintenance work, I'll be migrating from next-mdx-remote now that is resolved.

Arcath commented 3 years ago

No problem!

Glad to hear that mdx-bundler does what you need!