`Error importing react-markdown in Next.js 11.1 with TypeScript``

Having trouble with importing react-markdown in my next.js SSG project. When running npm run dev, I encounter an error that prevents me from proceeding to test in next export.

I understand that react-markdown is an esm package, but I'm not sure how to import esm into a non-esm project. Do I need additional packages? Note that I am not using tailwind css.

Any assistance on this issue would be greatly appreciated.

Server Error
    Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

    This error occurred during page generation. Any console logs will be displayed in the terminal window.
    Call Stack
    ReactDOMServerRenderer.render
    

package.json

{
        "browserslist": [
            ...
        ],
        "dependencies": {
            "autoprefixer": "^10.3.6",
            "axios": "^0.21.4",
            "next": "^11.1.2",
            "postcss-flexbugs-fixes": "^5.0.2",
            "postcss-normalize": "^10.0.1",
            "postcss-preset-env": "^6.7.0",
            "react": "^17.0.2",
            "react-dom": "^17.0.2",
            "react-markdown": "^7.1.0",
            "swr": "^1.0.1"
        },
        "devDependencies": {
            "@types/jest": "^27.0.2",
            "@types/react": "^17.0.25",
            "babel-jest": "^27.2.4",
            "express": "^4.17.1",
            "jest": "^27.3.1",
            "typescript": "^4.4.2"
        },
        "engines": {
            "node": ">=14.17.6",
            "npm": ">=6.14.15"
        },
        "name": "...",
        "private": true,
        "scripts": {
            "dev": "cross-env NODE_OPTIONS='--inspect' NODE_ENV='development' node server.js",
            "export": "next export",
            "start": "next start",
            "test": "jest"
        },
        "version": "0.1.0"
    }
    

next.config.js

module.exports = {
        ...
        experimental: {
            esmExternals: true, //also tried 'loose'
        }
        ...
    };
    

tsconfig.json

{
        "compilerOptions": {
            "allowJs": true,
            "allowSyntheticDefaultImports": true,
            "baseUrl": ".",
            "esModuleInterop": true,
            "forceConsistentCasingInFileNames": true,
            "isolatedModules": true,
            "jsx": "preserve",
            "lib": ["dom", "dom.iterable", "esnext"],
            "module": "esnext",
            "moduleResolution": "node",
            "noEmit": true,
            "downlevelIteration": true,
            "resolveJsonModule": true,
            "skipLibCheck": true,
            "strict": false,
            "target": "es5"
        },
        "exclude": ["node_modules"],
        "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
    }
    

component

import React from 'react';
        import ReactMarkdown from 'react-markdown';

        type TestComponentProps = {
            summaryTitle: string;
            markdownString: string;
        };

        export const TestComponent = ({ summaryTitle, markdownString }: TestComponentProps): JSX.Element => {
            return (
                <div className="container">
                    <h2 id="ratingsId">
                        {summaryTitle}
                    </h2>
                    <p>{markdownString}</p>
                    <ReactMarkdown>{markdownString}</ReactMarkdown>
                </div>
            );
        };
    

Answer №1

To ensure proper functioning, it is important to activate the ReactMarkdown module on the client side.

const ReactMarkdown = dynamic(() => import('react-markdown'), { ssr: false })

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

Can you determine the size of an unknown array in TypeScript?

Currently diving into TypeScript and tackling some TDD challenges. Within my model file, I'm working with a property named 'innovatorQuotes' that should be an array containing strings with a fixed length of 3. I'm struggling to nail dow ...

Encountering issues with MyModel.findOne not being recognized as a function while utilizing Mongoose within Next.js 14 Middleware

Within my Next.js middleware, I am encountering the following code: let user: UserType[] | null = null; try { user = await findUser({id}); console.log("user", user); } catch (error: any) { throw new Error(error) ...

Redirect middleware for Next.js

I am currently working on implementing a log-in/log-out feature in my project using nextjs, redux-saga, and mui libraries. // middleware.ts import { NextRequest, NextResponse } from 'next/server'; import { RequestCookies } from 'next/dist/c ...

Experiencing trouble with cross-origin resource sharing when attempting to transfer data to my server

"Access to XMLHttpRequest at 'http://localhost:3000/campgrounds/6411f03e718f68104cac045a' (redirected from 'http://localhost:5000/campgrounds') from origin 'http://localhost:3000' has been blocked by CORS policy: Response ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

TS7016: No declaration file was found for the module named 'rxjs'

I recently updated my Angular App dependencies and successfully installed them. However, I am now facing an issue with 'rxjs'. The IDE returned the following error: TS7016: Could not find a declaration file for module 'rxjs'.'C:/ ...

Is there an alternative method to handle the retrieval of JSON data without encountering numerous errors?

I'm currently in the process of instructing an LLM model to generate a blog. I used Mistral as the base model and set up an instruction to return JSON output. I then created a function that takes the prompt as an argument and returns generatedPosts as ...

The optimal location to declare a constructor in Typescript

When it comes to adding properties in an Angular component, the placement of these properties in relation to the constructor function can be a topic of discussion. Is it best to declare them before or after the constructor? Which method is better - Method ...

Tips for properly handling a property that receives its value from a callback function and waiting for it to be updated

Below is my TypeScript code: private getInfoSystem = () => { this.systemInfo = { cpuSpeed: 0 , totalRam: os.totalmem(), freeRam: os.freemem(), sysUpTime: os_utils.sysUptime(), loadAvgMinutes: { on ...

Discovering the category for ethereum, provider, and contract

My current interface looks like this: interface IWeb3 { ethereum?: MetaMaskInpageProvider; provider?: any; contract?: any; }; I was able to locate the type for ethereum using import { MetaMaskInpageProvider } from "@metamask/providers", ...

Enhancing User Experience with React-Redux: Implementing Subcategory Visibility based on Main Category Selection

How can I implement action logic to show and hide elements based on user interaction with main categories? Currently, all subcategories are being displayed at once, but I want them to be shown only when a user clicks on the corresponding main category. For ...

The link tag simply alters the link address without affecting the page display

Currently, I am delving into next js routing and facing a certain error. Whenever I click the Link tag, it simply alters the URL from "localhost:3000" to "localhost:3000/sample", but unfortunately, it does not display the "Hi" on my sample.js file. import ...

Setting up ESM for Firebase functions: A step-by-step guide

Our server application needs to utilize the most recent ipfs-http-client as it is an authorized package for accessing IPFS. However, the project must switch to using ESM starting from v57.0.0. I have invested a significant amount of time into this and it h ...

Definition of Promise resolve type in Visual Code's d.ts file

Need help with: // api.js export function getLayout(){ return axios.get('/api/layout').then(res => res.data) } // api.d.ts declare interface JSONResponse { meta: object, data: Array<Field> } export declare function getLayout ...

Issue with Angular 9 application: Unable to properly render form fields within a Material Design Dialog

I'm currently developing a "Tasks" application using Angular 9 and PHP. I've encountered an error that says Cannot find control with name: <control name> when attempting to pre-fill the update form with data. Here is the form template: &l ...

Is it advisable to encapsulate my entire Express server within a TypeScript class?

After working extensively with nodeJs, I have decided to explore developing applications in Typescript. Recently, I came across various blogs (like this one) that recommend wrapping modules and the app's entry point in a class when creating a RESTful ...

Next.js: rendering page components prior to fetching data in getInitialProps()

I have been working on a project using next.js with redux-saga. My goal was to fetch data before each page load by utilizing getInitialProps in next.js. The desired behavior of my application was: Visit localhost:3000 Redirect to the login page Fe ...

"Unlocking the Power of Groq: Revealing Referenced Objects in Style

My website has a section dedicated to showcasing "Success cases" with their own individual pages like /cases/some-slug. Each case is associated with a brand through the "cases" schema, which references a Brand entity: {title: 'Case Brand', ...

Ways to stop Next JS 13 from automatically preloading pages

While using my app that is connected to Firebase, I have noticed that each time a page loads, my usage count exceeds due to the Next JS preloading feature. This unexpected increase in cost is concerning. How can I prevent Next JS 13 from preloading? I susp ...

How do you obtain the string name of an unknown object type?

In my backend controllers, I have a common provider that I use extensively. It's structured like this: @Injectable() export class CommonMasterdataProvider<T> { private readonly route:string = '/api/'; constructor(private http ...