Having trouble compiling MDX files that include React Components?

I have implemented NextJS and MDX using next-mdx-remote to retrieve my data, and it's working successfully. However, I encounter an error whenever I try to import React components:

Error: Expected component CodeBlock to be defined: you likely forgot to import, pass, or provide it. It’s referenced in your code at 317:1-317:24

In summary:

This Works -

---
title: 'First Blog Post'
author: 'Me'
publishDate: 'Nov 4th, 2023'
---

# This is our first post

Here is a regular paragraph

here is a list:

- Item one
- Item two
- Item three

## This is an h2 element

This Does Not -

---
title: 'First Blog Post'
author: 'Me'
publishDate: 'Nov 4th, 2023'
---

# This is our first post

Here is a regular paragraph

here is a list:

- Item one
- Item two
- Item three

<CodeBlock></CodeBlock>

## This is an h2 element

Here are the relevant files:

  1. index.js for MDX

https://pastebin.com/5ZmCDtkf

  1. articles/[slug]/page.js

https://pastebin.com/X0tGqsip

  1. package.json

https://pastebin.com/iNCywNfK

Updated:

  1. mdx-components.js

https://pastebin.com/U8Bn739q

Answer №1

It seems that there is a minor error in your index.js file for MDX. When calling the compileMDX function, components should not be enclosed in extra curly braces:

const { frontmatter, content } = await compileMDX({
    source: fileContent,
    options: { parseFrontmatter: true },
    components: components // <--- remove the curly braces
})

Complete code snippet:

import fs from 'fs'
import path from 'path'
import { compileMDX } from 'next-mdx-remote/rsc'
import CodeBlock from "../../app/elements/CodeBlock";
import InfoPanel from "../../app/elements/InfoPanel";
 
const rootDirectory = path.join(process.cwd(), 'src/app', 'mdx-pages')
 
const components = {
  // Add component definitions here
  CodeBlock,
  InfoPanel,
};
 
 
export const getPostBySlug = async slug => {
  var 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 },
    components: components // <--- remove the curly braces
  })
 
  return { meta: { ...frontmatter, slug: realSlug }, content }
}
 
export const getAllPostsMeta = async () => {
  const files = fs.readdirSync(rootDirectory)
 
  let posts = []
 
  for (const file of files) {
    const { meta } = await getPostBySlug(file)
    posts.push(meta)
  }
 
  return posts
}

Answer №2

Based on the information found in the next-mdx-remote documentation mentioned here:

The document states that import and export statements are not allowed within an MDX file. To incorporate components into MDX files, they must be passed as a prop to <MDXRemote />.

It appears that this approach is taken because next-mdx-remote is designed to fetch content from anywhere rather than just local sources, hence local imports are not directly supported.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in next.js when navigating to a different route with incorrect image being

I am experiencing an issue with my [trainers].tsx page where the data loads correctly, but the image does not load properly. Instead, I can see a previous image from another page (../2) before the correct image is displayed. For instance, when I navigate ...

Trouble accessing session cookie during server-side request with getServerSideProps in Next.js

I'm currently facing an issue where I am trying to make a request to a backend service using Axios in getServerSideProps, but it is unsuccessful because the necessary session cookie for authentication is not included in the context.req headers. In th ...

Is there a way to position the Image component from next/image using absolute positioning?

Is it possible to use an element Image from 'next/image' with the CSS style { position: absolute; left: 50% }? It appears that it is not being applied. For example: import React from 'react' import Image from 'next/image' imp ...

Creating multilingual URLs in Next.js for both Latin and non-Latin languages

Our team is embarking on creating a react web app using next.js, but we're facing a challenge with implementing multilanguage URLs. Our objective is to ensure that the same content in different languages has unique URL slugs. For instance, www.tld.com ...

When transferring the code to the src folder, tRPC encounters issues and stops functioning

Currently, I am working on developing a basic Twitter clone using Next and TRPC. While tRPC is up and running smoothly, I am looking to streamline my code by consolidating it all within the src directory. However, upon moving everything, I encountered an i ...

Low scoring performance in Lighthouse on a nearly empty page built with Next.js

While working on my Next.js project locally, I used npm run dev for development. After testing my website, I noticed that it scored a 40 in Performance. https://i.stack.imgur.com/3jmro.png Despite trying to use Lighthouse in secret mode, the results rem ...

Establish the default sorting for Material UI tables

I'm struggling with setting the default sorting for a Material UI table. Is there a more straightforward way to do this without using a button at the top? I want the table to automatically sort by protein when it is loaded. import * as React from &apo ...

Creating a cookie within nextjs version 14

In developing my Next.js app, I encountered a challenge while setting up the authentication/authorization system. My approach involved using a refresh token with a long duration stored in an httpOnly cookie, along with an access token with a short duration ...

When trying to debug the client of a NextJS 12 app in VSCode, breakpoints refuse to be hit

Having trouble debugging NextJS 12 apps in VSCode. Breakpoints not triggering upon browser reload. To create a default NextJS 12 app, use: $ npx create-next-app@latest. Create the launch.json using https://nextjs.org/docs/advanced-features/debugging: { ...

The complex hierarchical structure of Gallery, Exhibit, Painting, and ExhibitPaintingDetail creates a multi-layered entity relationship system

For the ERD of the tables involved in this project, please refer to This project uses Next.js and TypeORM. Can you explain how the relationships work in the entities Exhibit, Painting, and ExhibitPaintingDetail? The Postgres tables have foreign keys from ...

Hey there! I'm currently facing some difficulties with storing form input data into a nested json file

I have developed a Next.js application with a form component structured as follows: components/Form.js import { useState } from 'react' import { useRouter } from 'next/router' import { mutate } from 'swr' const Form = ({ for ...

Unable to make a POST request to the express API using the next.js API route (nextauth)

Currently, I have an express server running on port 8080 and my NextJS app running on port 3000. To handle user authentication, I am utilizing nextauth which involves sending username and password credentials to the express API on port 8080 for validation. ...

Incorporating dynamic data into the main page of NextJs by pulling information from various files

I'm currently facing difficulties while trying to integrate dynamic data from one file into another. The data I am attempting to fetch is located at: path: /src/components/Subnav.js import React, { Component } from "react"; class Subnav ex ...

Trouble with CORS blocking NextJs from fetching data from Prismic

I'm encountering an issue while trying to fetch and display lists of my content on a simple blog. Every time I attempt to run the code, it gives me a CORS error message stating that my request has been blocked. It's frustrating because all I wan ...

Ways to incorporate a language switcher with next-intl

"use client"; import { useLocale } from "next-intl"; import { locales, localeNames } from "../../i18nconfig"; import { useRouter } from "next/router"; import Link from 'next/link'; import { Fragment } from ...

Is it possible to integrate two calendars into the `DatePicker` component of MUI?

The <DateRangePicker/> component from MUI has a prop called calendars which determines the number of calendars displayed inside the component popup. Here is an example: If the calendars prop has a value of "3", it will look like this: https://i.sta ...

What could be causing the parameters to be empty in Next.js static site generation with getStaticProps?

Introduction I am currently in the process of developing an application using next.js, specifically utilizing its static site generation feature. Despite following various examples and documentation for hours, I am encountering an issue where the params o ...

Comparing Amazon Fargate and EC2 for hosting container-based websites

In a recent project, I was tasked with building a React / NextJS application that will experience occasional high traffic but mostly remain idle. Our goal is to find the most cost-effective options while still creating a scalable and manageable app with a ...

Error encountered while installing Material UI in Next.js with TypeScript and pure JavaScript configurations

I'm brand new to React and Next.js, so please forgive me for asking what may seem like a silly question. I'm attempting to install Material UI in a fresh Next.js application that I created using "npx create-next-app@latest". I've been refere ...

"Encountered an error of 'Authentication failed' while trying to access a blob using the SAS

My team and I are currently in the process of developing a NextJS web app, and we have recently integrated Azure Blob Storage for file upload and display. I am tasked with working on displaying images on the frontend. To achieve this, I am using the genera ...