Search code examples
javascriptnode.jsreactjswebpack

How to export multiple components from an index file in React?


Here is my index.jsx file:

import Navbar from './Navbar/Navbar';
import Greeting from './Greeting/Greeting'
import Project from './Project/Project';
import About from './About/About';
import Contact from './Contact/Contact';
import Footer from './Footer/Footer';

export default {
  Navbar,
  Greeting,
  Project,
  About,
  Contact,
  Footer,
};

And my App.jsx file:

import React from 'react';
import {Navbar} from './components';

// import Navbar from './components/Navbar/Navbar';

const App = () => {
  return (
    <div>
      <Navbar />
    </div>
  )
}

export default App;

When I call to import Navbar through the index.jsx file, I got this error:

Uncaught SyntaxError: The requested module */sre/components/index. isx? App.isx:4 t=1672200538218' does not provide an export named "Navbar'

What wrong I got if I call Navbar through index file? Thank you so much!

How can I call to import many components througnt index file.


Solution

  • Instead of importing them and then exporting them, you could directly export them as below. But for this to work you would want to use named exports, like export function Navbar() instead of export default function Navbar().

    export { Navbar } from "./Navbar/Navbar";
    export { Greeting } from "./Greeting/Greeting";
    export { Project } from "./Project/Project";
    export { About } from "./About/About";
    export { Contact } from "./Contact/Contact";
    export { Footer } from "./Footer/Footer";
    

    But if you would rather keep your default export, you should be doing as below instead of what you have:

    export { default as Navbar } from "./Navbar/Navbar";
    export { default as Greeting } from "./Greeting/Greeting";
    export { default as Project } from "./Project/Project";
    export { default as About } from "./About/About";
    export { default as Contact } from "./Contact/Contact";
    export { default as Footer } from "./Footer/Footer";
    

    You can learn more about export on mdn.