DEV Community

loading...
Cover image for Export React child components from single file

Export React child components from single file

Pere Sola
Account Manager @Stripe during the day. Full stack software developer after-hours. @LambdaSchool graduate
・2 min read

When coding a React app, I always find it anoying having to import each child component one line at a time, often in several files. This takes lines of code and is not DRY.

import Login from './Components/Login';
import Signup from './Components/Signup';
import BlaBla from './Components/BlaBla';
Enter fullscreen mode Exit fullscreen mode

Moreover, you cannot do CTRL + space bar to see what names are available for import. It would be so much handy if I could do something like:

import { Login, Signup, BlaBla } from './Components/Singlefile'; 
Enter fullscreen mode Exit fullscreen mode

You can by creating what I call a exporter file (I just made it up). The file would be something like:

import Login from './Login';
import Signup from './Signup';
import BlaBla from './BlaBla';

export { Login, Signup, BlaBla };
Enter fullscreen mode Exit fullscreen mode

So in the rest of the files where Components need to be imported, it is just a line of code:

import { Login, Signup, BlaBla } from './Components/Exporter';
Enter fullscreen mode Exit fullscreen mode

And you can use the CTRL + Space bar within the { } to find what you are looking for without typing. You still need to type all imports in the Exporter file but you will only have to do it once.

Edit

User @futureistaken pointed me to re-exports. I had no clue about it, so I googled it and found a nice explanation here. Basically it is a way to import and export in a single line. In my case, because I am exporting my components with export default it would be:

export { default as Login } from './Login';
export { default as Signup } from './Signup';
Enter fullscreen mode Exit fullscreen mode

Otherwise, it would be:

export { Login } from './Login';
export { Signup } from './Signup';
Enter fullscreen mode Exit fullscreen mode

Nicer and sweeter!

Discussion (2)

Collapse
futureistaken profile image
R Z

It is so pity that you don't know about re-export. Google it and you will be very impressed.

Collapse
petrussola profile image
Pere Sola Author

oh, nice, looks shorter and sweeter indeed javascript.info/import-export#re-e... thanks for sharing it