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:
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"; |
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.
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"; |
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; |
Thanks and don't forget to live a ❤️ !
Top comments (0)