4

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?

1
  • 1
    try adding an example and then asking what is the logic, your question is too abroad Commented Jun 10, 2019 at 19:33

3 Answers 3

3

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';
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.