DEV Community

Cover image for Export React child components from single file
Pere Sola
Pere Sola

Posted on

6 2

Export React child components from single file

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (3)

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

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

Collapse
 
mukadas profile image
Mukadas Maltiti

Thanks, I was struggling to export some images, this helped a lot

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

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay