DEV Community

Cover image for Clean Code: Multiple exports, single import!
Mwenedata Apotre
Mwenedata Apotre

Posted on

Clean Code: Multiple exports, single import!

I always wondered whether there is a cool way to import many components in one line in React JS once they are in the same folder.And turns out there is a way that you can make your component more cleaner and will save you a lot of frustation.

So let's say you have 5 Components in your app and they are stored in a folder called components. Like this folder structure below:

folder structure for components in a ReactJS project

The problem(issue)

The issue here is that if you want to import all the components on a single page like home page you'll need to write this:

You can see that if we need to import many files like 20 components our file is cluttered with import rather than the real logic it need to implement.

Quick Solution

Create a file named index.js inside the components folder.

Index file created

And then paste in the above codes from home to that newly created index.js file:

Then what you have to do is export the files as named exports from the index.js file:

So, you see that was very easy and now you have a clean home page file like so:

Thanks and don't forget to live a ❤️ !

Top comments (0)