When combining NextJS, Rollup, and yalc, an error may occur stating "Element type is invalid: expected a string (for built-in components) but got: undefined."

While working on creating a component library for React, I keep encountering the following 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.

Check the render method of `MyApp`.

My setup involves using rollup to bundle the library and yalc to link the local dependency into a nextjs project located in a different directory. Everything seems to import fine except for a React Context. Both projects are utilizing react and react-dom version 17.0.2.

I've simplified the components as much as possible.

index.tsx (from the component library)

const TestContext = React.createContext<TextContextValues>({} as TextContextValues);
const ProviderWrapper = ({ children }: Props) => {
    const value = {};
    return <TestContext.Provider value={value}>{children}</TestContext.Provider>;
};

const Wrapper = ({ children }: Props) => {
    return <div>{children}</div>;
};

// EXPORT
export { ProviderWrapper, Wrapper };

In the _app.tsx file for the nextjs project, the code looks like this:

import { ProviderWrapper, Wrapper } from '@package-name-from-yalc';
import type { AppProps } from 'next/app';
import React from 'react';

import '../styles/globals.css';

function MyApp({ Component, pageProps }: AppProps) {
    return (
        <ProviderWrapper>
            <Component {...pageProps} />
        </ProviderWrapper>
    );
}

export default MyApp;

The above code snippet produces an error when navigating to a page, while the below code snippet does not:

import { ProviderWrapper, Wrapper } from '@package-name-from-yalc';
import type { AppProps } from 'next/app';
import React from 'react';

import '../styles/globals.css';

function MyApp({ Component, pageProps }: AppProps) {
    return (
        <Wrapper>
            <Component {...pageProps} />
        </Wrapper>
    );
}

export default MyApp;

It's puzzling to me why this inconsistency exists since both components are created and exported in the same manner, and they both wrap and pass down the children.

Below is my rollup.config.js for reference:

import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import postcss from 'rollup-plugin-postcss';
import { terser } from 'rollup-plugin-terser';
import typescript from 'rollup-plugin-typescript2';
import pkg from './package.json';
const tailwindcss = require('tailwindcss');

export default {
    input: 'src/index.tsx',
    output: [
        {
            file: pkg.main,
            format: 'cjs',
            sourcemap: true,
        },
        {
            file: pkg.module,
            format: 'es',
            sourcemap: true,
        },
    ],
    external: [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {}), 'react'],
    plugins: [
        peerDepsExternal(),
        postcss({
            plugins: [
                tailwindcss('./tailwind.config.js'),
                require('autoprefixer'),
                require('cssnano')({ preset: 'default' }),
            ],
        }),
        resolve(),
        typescript({
            useTsconfigDeclarationDir: true,
            rollupCommonJSResolveHack: true,
            exclude: ['**/__tests__/**', '**/*.stories.tsx'],
            clean: true,
        }),
        commonjs({
            include: ['node_modules/**'],
        }),
        terser(),
    ],
};

Answer №1

It appears that one of the components in your app's component tree may have failed to render, even if you are using return <></>. This issue could arise due to an unresolved import statement in a component or due to an error preventing the component from reaching the return code.

If you're fortunate, the error message from NextJS will guide you to inspect the render method of a specific component.

If not, consider temporarily commenting out components starting from the top level and proceeding downwards to identify the problematic one.

UPDATE: There seems to be a compiling bug in NextJS (currently on v12.0.8). While importing a component might trigger the error message, adding a console.log() line to the error component and saving it can prompt a fast refresh on the same page, resolving the issue.

Answer №2

modify the following line

import type { AppProps } from 'next/app';

as follows

import { AppProps } from 'next/app';

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

Strategies for Handling Various Versions of npm Modules within a Project when Multiple Packages Depend on Specific Versions Internally

I find myself in a predicament with my main React project using version "1.5.1" of "@material-ui/core", while attempting to build a new component that requires version "3.2.1" of "#@rjsf/material-ui" which internally relies on the latest version of "@mater ...

Executing functions in real-time using React Native

I'm fairly new to Object-Oriented Programming (OOP) and my understanding of promises, asynchronous/synchronous function execution is quite basic. Any guidance or help from your end would be greatly appreciated! Let's take a look at an example fr ...

Retrieve the value of material user interface buttons

I am facing a challenge with Material UI. I have two buttons with values, and I want to run a function that console logs the value when someone clicks on them. However, when using e.target.value in Material UI, it returns undefined. While searching for a ...

Is there a way to eliminate black borders from a pop-up window?

When working with material UI, I noticed that the default import of a component includes black borders. Is there a way to modify the code so the box is completely white without any black borders? Looking for a snippet that can help me achieve this. Curren ...

How do you vertically span a grid element across 3 rows using Material UI?

This particular scenario may appear to be straightforward, but the official documentation of Material UI lacks a clear example on how to achieve this. Even after attempting to nest the grid elements, I encountered an issue where the grid element on the ri ...

A guide to creating a dynamic form using Material-UI components in React Redux: How can I easily add and manage input fields?

Currently, I am in the process of updating my code from a React-Flux-Bootstrap application to Redux with Material-ui. My main goal is to create a form that initially has one input field (e.g., title) and then allows users to add multiple extra inputs by cl ...

How to enhance and expand Material-UI components

I am trying to enhance the Tab component using ES6 class in this way: import React from "react"; import {Tab} from "material-ui"; class CustomTab extends Tab { constructor(props){ super(props); } render(){ return super.rende ...

The clerk encountered difficulty retrieving the publishable key from the environment variables within Next.js version 13

I recently developed a website using Next 13 (an experimental app directory) and integrated authentication with Clerk. While everything runs smoothly on my local environment, once deployed to Netlify, the site fails to load. Upon checking the console, I e ...

Every time Tailwind compiles, it seems to generate a glitchy class

There was a time when I accidentally wrote 2 classes without a space max-w-[412px]mb-[36px]. This caused an error, so I added a space between the classes. However, the error persisted even after making this correction. In a last attempt to resolve the issu ...

Compilation unsuccessful. The LineGraph.js module could not be located due to recursion in resolving

After successfully installing react-chartjs-2 and chart.js using the command npm install --save react-chartjs-2 chart.js, I encountered an error when attempting to use LinkGraph: Failed to compile. ./src/LineGraph.js Module not found: Recursion in resolvi ...

Issue with Responsive Font Size functionality in Tailwind and ReactJS not functioning as expected

I'm really struggling with this issue. I grasp the concept of mobile-first design and have successfully made my website's layout responsive. However, I'm having trouble getting the font size to change when applying breakpoints as the screen ...

React and Express application facing issue with JSX rendering restriction

I've been delving into the world of web app development with Express, but I'm struggling to grasp how it transmits data to the client side and what its main function is. My understanding is that Express is responsible for sending data to the clie ...

Does Next.js Hot Reload come with a preliminary hook?

Every time the application undergoes a Hot Reload, it initiates the creation of a fresh database connection pool using node-mysql2 for reusing DB connections. However, with each Hot Reload, a new pool is formed, ultimately causing the RDBMS to hit its maxi ...

Adjust the width of the lower drawer component using React

After some extensive searching, I've hit a roadblock trying to tweak the width of an imported Material UI Drawer Swipeable edge. My aim was to make it Bottom-type without spanning the entire screen. I managed to adjust the top width using sx. However ...

Tips on activating the CSS style while typing using the onChange event in React

Is it possible to dynamically adjust the width of an input as we type in React? Currently, my input has a default width of 1ch. I would like it to increase or decrease based on the number of characters entered, so that the percentage sign stays at the end ...

A step-by-step guide on setting up flow types for @material-ui/core version 4

Is there a way to install flow types for material-ui/core version 4.x.x? It seems like the last update was for version 1.x.x here. The documentation on this topic is quite limited here. I'm unsure if there is still support for this, especially since t ...

What is the reason behind the restriction on using capital letters in React project names?

When attempting to create a new project "newRecipeApp" in React, I encountered the following message: npx: installed 91 in 29.359s Could not create a project called "newRecipeApp" because of npm naming restrictions: * name can no longer contain capital ...

What is the process of setting up a proxy for Clerk authentication in a Next.js/Vercel application?

Following the Clerk documentation has been a bit challenging as it seems to lack some crucial information: In my simple Next.js 14 app using the app router pattern and app directory, they mention adding 3 headers to the proxy: Clerk-Proxy-Url: Should con ...

Having trouble executing a fetch request in Next.js

I am struggling to perform a fetch request using getStaticProps in Next.js. Despite following the documentation provided on their website, I am unable to console log the props successfully. My background is mainly in React, so I tried to adapt my approac ...

Using multiple functions to organize nested variables within the useState hook

I'm stuck trying to figure out a part of my application, leading me to have some questions. I am working with a JSON string from an API as input for my project. This JSON string needs to generate multiple input fields on the page, which I then plan to ...