DEV Community

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

Posted on

4 1

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:

import Footer from "../components/footer";
import Like from "../components/like";
import Navbar from "../components/navbar";
import Sidebar from "../components/sidebar";
import Card from "../components/card";
view raw Home.jsx hosted with ❤ by GitHub

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:

import Footer from "../components/footer";
import Like from "../components/like";
import Navbar from "../components/navbar";
import Sidebar from "../components/sidebar";
import Card from "../components/card";
view raw index.jsx hosted with ❤ by GitHub

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

import Footer from "../components/footer";
import Like from "../components/like";
import Navbar from "../components/navbar";
import Sidebar from "../components/sidebar";
import Card from "../components/card";
export {
Footer,
Like,
Navbar,
Sidebar,
Card
}

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

import {Footer,Sidebar,Navbar,Like,Card} from '../components';
const Home = ()=>{
return <Footer></Footer>
}
export default Home;
view raw homeUpdated.jsx hosted with ❤ by GitHub

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs