I've been attempting to integrate custom components into my .mdx
posts using the mdx-components.js
file, however, the custom components are not being displayed.
Here's the code from my mdx-components.js
file, which I created following the guidelines from the NextJS documentation:
// my-blog/mdx-components.js
import UnderlineHoverLink from "./app/_components/Links/UnderlineHoverLink";
export function useMDXComponents(components) {
return {
a: ({ href, children }) => (
<UnderlineHoverLink href={href}>{children}</UnderlineHoverLink>
),
...components,
};
}
Below is the code that renders the .mdx
files on my page:
// my-blog/app/(routes)/posts/[slug]/page.js:
import { getPostBySlug } from "@/app/_lib/mdx";
const getPageContent = async (slug) => {
const { meta, content } = await getPostBySlug(slug);
return { meta, content };
};
export async function generateMetadata({ params }) {
const { meta } = await getPageContent(params.slug);
return { title: meta.title };
}
const Page = async ({ params }) => {
console.log(params);
const { content } = await getPageContent(params.slug);
return content;
};
export default Page;
And here's the code snippet responsible for fetching the content from the filesystem where the .mdx
files are located:
// my-blog/app/_lib/mdx/index.js
import fs from "fs";
import path from "path";
import { compileMDX } from "next-mdx-remote/rsc";
const rootDirectory = path.join(process.cwd(), "content/posts");
export const getPostBySlug = async (slug) => {
const realSlug = slug.replace(/\.mdx$/, "");
const filePath = path.join(rootDirectory, `${realSlug}.mdx`);
const fileContent = fs.readFileSync(filePath, { encoding: "utf8" });
const { frontmatter, content } = await compileMDX({
source: fileContent,
options: { parseFrontmatter: true },
});
return { meta: { ...frontmatter, slug: realSlug }, content };
};
As mentioned in the NextJS documentation:
By defining styles and components in mdx-components.tsx, changes will be reflected across all MDX files within your application.
Despite following the documentation closely, I'm unable to successfully render my custom link. If anyone could offer assistance with troubleshooting, it would be greatly appreciated.
I've examined the HTML output in the browser to check if the custom link is being displayed but possibly being overridden by other styles. However, it appears that the custom link is not rendering at all. I even attempted removing the mdx-components.js
file to test if it was being loaded, and NextJS raised an error, confirming that the file is being loaded.