DEV Community

Cover image for Export Multiple Components in Index File
CY
CY

Posted on • Originally published at cyishere.dev

Export Multiple Components in Index File

Export Multiple Components

When I structure a React app, I'd like to put the components which are in the same category but with different styles in the same folder. Something like this:

/- components
    /- Card
        /- CardLeftMedia.js
        /- CardRightMedia.js
        /- CardTopMedia.js
Enter fullscreen mode Exit fullscreen mode

So, I need to import & export them in a index.js file. Here's the simple solution:

// components/Card/index.js

export { default as CardLeftMedia } from "./CardLeftMedia";
export { default as CardRightMedia } from "./CardRightMedia";
export { default as CardTopMedia } from "./CardTopMedia";
Enter fullscreen mode Exit fullscreen mode

They're named exports, and I import them with curly braces:

// pages/Home.js

import { CardLeftMedia } from "../components/Card";
Enter fullscreen mode Exit fullscreen mode

Export One Component as Default

There's another scenario like this:

/- components
    /- Card
        /- Card.js
        /- Card.module.css
Enter fullscreen mode Exit fullscreen mode

To export Card.js, I also add an index file:

// components/Card/index.js

export { default } import "./Card";
Enter fullscreen mode Exit fullscreen mode

It's a default export and I could import it directly:

// pages/Home.js

import Card from "../components/Card";
Enter fullscreen mode Exit fullscreen mode

More information about ES6 modules: ECMAScript 6 modules: the final syntax.

Top comments (0)