I am building a Next.js project and I get 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.
When trying to import Layout component into my _app.js, but got the above error.
_app.js
import React from "react";
import "@/styles/globals.css";
import Layout from "@/components";
export default function App({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
}
Layout.jsx
import Head from "next/head";
import React from "react";
import { Navbar } from "./Navbar";
import { Footer } from "./Footer";
const Layout = () => {
return (
<div className="layout">
<Head>
<title>Ecommerce Store</title>
</Head>
<header>
<Navbar />
</header>
<main className="main-container">empty</main>
<footer>
<Footer />
</footer>
</div>
);
};
export default Layout;
index.js – I created this single file to export all components
export { default as Footer } from "./Footer";
export { default as Layout } from "./Layout";
export { default as Navbar } from "./Navbar";
export { default as Product } from "./Product";
export { default as HeroBanner } from "./HeroBanner";
export { default as FooterBanner } from "./FooterBanner";
export { default as Cart } from "./Cart";
Components folder structure
I found similar solutions for this. But none of that helped.
(React) Element type is invalid, expected a string (for built-in components) or a class/function but got
2
Answers
The error is in the layout component, import Navbar and Footer with curly braces. When we aren't exporting a component as a default export and trying to import it as a named import (wrapped in curly braces) or vice versa because this is a common cause of the error.
Importing from a file that is located in the same directory. If we need to import from one directory up, we would do:
As the error message says, I think you forgot to export a component somewhere. I see that you are exporting Layout correctly. Are you doing the same in the Navbar and Footer components?