How to import all components in React?

Well, I have gone through what you have; I feel what you actually needed is to understand the reason for doing that. I am pretty sure what you want to achieve is to have your components imported from a single file rather than from the files where the components were exported.

You don't want to do this:

import NavBar from 'src/modules/layout/NavBar';
import SideBar from 'src/modules/layout/SideBar';

But what you want is to import all your components from a single file wherever you would want to use them. So, if that is the case, you don't need to add more complexities. All you just need to do is:

// export the components like this
export default NavBar;
export default SideBar;

// Then, in your src/modules/layout/index.js file, import // the components you exported just the way you did it

import NavBar from './NavBar';
import SideBar from './SideBar';

export {
NavBar,
SideBar
}

// Hence, wherever you need both components, you can easily do this:
import { NavBar, SideBar } from '../index.js'

// From the above, you are just importing both components from the index.js file. 

So, I believe that answers your question.


Just to add to Onyekachi Samuel's answer and to answer the all part of the title:

After creating the src/modules/layout/index.js file as he described, you can import all by:

import * as All from './layout'

And use the exported components:

<All.NavBar/> <All.SideBar/>

For instance:

// Folder structure:
//    |-App.js
//    |-Layout
//        |-NavBar.js
//        |-SideBar.js
//        |-index.js


// App.js in the same location as Layout folder

import React from 'react';
import * as All from './layout'

export default function App(props) {

    return (<div>
                <All.NavBar/>
                <All.SideBar/>
           </div>)
}

Hope this might clarify it for some.

Tags:

Reactjs