Reputation: 33
So I am developing a site on React and trying to organize BrowserRouter, so for every component(page) I create a path in App.js like this
<Route exact path="/" component={Homepage} />
<Route path="/about" component={About} />
and I would like to add multiple components to create multiple routes like that. The question is, is there an efficient way to handle multiple imports from ONE folder that contains only .js files. I have a folder "./articles" and for every single file I want to export I do this now
import MyComponent1 from "./articles/MyComponent1.js";
Repeating this line only changing the last parameter doesn't seem right. Is there a trick for import that can make it more efficient?
Upvotes: 1
Views: 4554
Reputation: 119
If articles are different only by its content, but the structure is the same, I would suggest creating just one general 'Article` component that will show different stuff based on provided props and you can store the info of the article in some JSON or backend in some array and iterate over that. That will allow you to write the code once and just populating the array of articles with no need to maintain imports. Hope this helps!
Upvotes: 0
Reputation: 1833
You can resolve this situation with node js (emulate import *
):
fs.stat
library with your componentsfs.writeFile
file with all of this componentsUpvotes: 0
Reputation: 5639
You can add an index.js
file into the /articles
directory and let that index.js
file import and export all classes in the folder. Afterwards you can import all of the exports from the same path.
Upvotes: 1
Reputation: 85102
If you want, you could make an index.js file in articles who's sole job is to collect the various components and export them from a single location. For example:
// /articles/index.js
export { default as MyComponent1 } from './MyComponent1.js';
export { default as MyComponent2 } from './MyComponent2.js';
export { default as MyComponent3 } from './MyComponent3.js';
export { default as MyComponent4 } from './MyComponent4.js';
// Used in another file:
import { MyComponent1, MyComponent2, MyComponent3, MyComponent4 } from './articles';
Upvotes: 7