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

Time:12-29

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.

CodePudding user response:

Instead of importing them and then exporting them, you could directly export them as below. But for the above solution to work you should 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 (which I wouldn't prefer, as anyway a named export is way better):

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

You can learn more about export on mdn.

  • Related