Why create both index.js and Component.js for one component in React?

Viewed 1246

While studying some projects I repeatedly find that authors follow a file structure that doesn't make sense to me without context.

For example, for any given component there would be a folder Header. There would be two files, one Header.js, and the other index.js (in the same subfolder). Both would export default const, but the index.js would also import the adjacent Header component.

What is the logic behind this structure?

3 Answers

This is a common pattern to avoid imports that look like this when you group things (tests, components, actions, reducers, etc...) together in sub-folders:

// src/
//  components/
//    Header/
//      index.js
//      Header.js
//      Header.test.js

import Header from 'components/Header/Header';

in favor of:

import Header from 'components/Header';

I know at least one reason not putting component's code into index.js: by now Jest does not allow having several manual mocks with the same name(but different paths! see https://github.com/facebook/jest/issues/2070 for details).

So

//- src
//-- Component1
//--- __mocks__
//---- Component1.js
//--- index.js
//--- Component1.js
//-- Component2
//--- __mocks__
//---- Component2.js
//--- index.js
//--- Component2.js

Will give both: shorter/more readable import(because of index.js) and working manual mocks in jest(because of component file name assumed to be unique across mock files in project)

This architecture pattern is called barrel. You can read more here: React barrels. The main purpose is to simplify the export of the components.

By using an index.js file in the root of each folder to re-export a subset of files, you can effectively create explicit public interfaces for your React modules.

Related