`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

Combining data types to create a unified set of keys found within a complex nested structure

This problem is really testing my patience. No matter what I do, I just can't seem to make it work properly. Here's the closest I've come so far: // Defining a complex type type O = Record<'a', Record<'b' | 'x& ...

Using mergeMap in conjunction with retryWhen allows for the resumption of retries from the exact point of failure, without needing

I have a list of URLs, the number of which is unknown until it stops (depending on some condition). This is how I am currently using them: from(observableUrls) .pipe( mergeMap(url => callHttpService(url) , 4), retryWhen( // Looking f ...

Using a dictionary of objects as the type for useState() in TypeScript and React functional components

I am in the process of transitioning from using classes to function components. If I already have an interface called datasets defined and want to create a state variable for it datasets: {[fieldName: string]: Dataset}; Example: {"a": dataset ...

Implement a feature in NextJS where an MP3 file is played upon clicking

Just getting started with JS frameworks and having some trouble with the function syntax. Here's what I have so far: when the button is clicked, it should play a quick audio file specified below the button in the Audio tags. Any suggestions on how to ...

Nextjs version 13 is throwing a TypeError due to trying to read properties from null, specifically trying to read the 'length' property

Currently, I am in the process of learning how to build a Next.js application through a helpful tutorial on Egghead. I've hit a roadblock at lesson 4, where the tutorial covers retrieving data from a Supabase database. I suspect that my issue may be ...

Typescript raises a error notification regarding the absence of a semicolon when importing a JSON module

Attempting to import a local JSON object into my Vuex store using const tree = import('@/articles/tree.json');. The setting "resolveJsonModule": true, has been enabled in my tsconfig.json and it loads successfully, however NPM is flooding the out ...

Run a script in a newly opened tab using the chrome.tabs.create() method

Struggling with executing a script using chrome.tabs.executeScript() in the tab created with chrome.tabs.create()? Despite searching for solutions, nothing seems to be working as expected. Check out my current code below: runContentScript(){ c ...

Add one string to an existing array

I have a component named ContactUpdater that appears in a dialog window. This component is responsible for displaying the injected object and executing a PUT operation on that injected object. The code for the component is shown below: HTML <form [for ...

"Encountering issues with importing Splitpanes while using VueJs and TypeScript combination

My VueJS view was originally written in JavaScript using the component "splitpanes" from npm package. The code was functioning well with the following structure: <template> <div> <Splitpanes :dbl-click-splitter="false" :horizont ...

Error message: Object literal is limited to declaring existing properties

The source code was obtained from this Codesandbox demo: CodeSandbox - Cover Image Example Subsequently, an .eslintrc configuration file was generated with the following content (the only content present): { "extends": "react-app" } However, a TypeScri ...

Is there a way to create a universal getter/setter for TypeScript classes?

One feature I understand is setting getters and setters for individual properties. export class Person { private _name: string; set name(value) { this._name = value; } get name() { return this._name; } } Is there a w ...

The issue of Next.js public/assets/css not loading is commonly experienced on dynamically generated pages

I am in the process of developing a Next.js application and have decided to start from an HTML template. All the necessary assets have been included in both my Head and _document.js files as shown below: <Head> <meta name="viewport" ...

Tally up identical words without considering differences in capitalization or extra spaces

Let's take an example with different variations of the word "themselves" like "themselves", "Themselves", or " THEMSelveS " (notice the leading and trailing spaces), all should be considered as one count for themselves: 3 ...

In TypeScript version 2.4.1, the fontWeight property encounters an error where a value of type 'number' cannot be assigned to the types of '"inherit", 400'

When attempting to set the fontWeight property in TypeScript, I encounter the following error: Types of property 'test' are incompatible. Type '{ fontWeight: number; }' is not assignable to type 'Partial<CSSProperties>&a ...

Over-reliance on the use of the useTranslation() hook

Currently, I am implementing next-i18next for translating my Next.js pages. I am contemplating whether using const { t } = useTranslation('common') in every react component would potentially impact performance negatively. Another option is to cal ...

Configuring React Testing Library with Next.js, GraphQL, Apollo, and internationalization (i18n) - Encountering issues with property

I am facing a challenge in setting up React Testing Library for a project that incorporates NextJS, GraphQL, Apollo, and i18n Initially, the Terminal flagged an issue with the router not being configured, so I resorted to using next-router-mock to simulat ...

Angular 6 Calendar Template issues with parsing: Unable to link to 'view' as it is not recognized as a valid property of 'div'

I am in the process of developing an application that utilizes this angular calendar. My tech stack includes Angular 6 with AngularFire2 and Firebase. Below is my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; imp ...

Even when there is a change in value within the beforeEach hook, the original value remains unchanged and is used for dynamic tests

My current project setup: I am currently conducting dynamic tests on cypress where I receive a list of names from environment variables. The number of tests I run depends on the number of names in this list. What I aim to achieve: My main goal is to manip ...

Is there a way to automate the importing of a server-fetched icon in NextJS?

I am looking to automatically generate a dynamic page within the Next-JS app. This page should include Icons that are fetched from the server instead of being hardcoded: { "id": 1, "title": "Budget", "value ...

Typescript encountering issues with addEventListener

const [status, setStatus] = useState<string>("pending"); const updateStatus = (newStatus: string) => { setStatus(newStatus); }; useEffect(() => { window.addEventListener("updateProtocol", updateStatus); return () =&g ...