javascript – Why do we need index.js for components?


In the process of learning React, I came across many examples in which the following structure is present:

├─ src/components/ExampleComponent
   ├── ExampleComponent.js 
   ├── ExampleComponent.test.js 
   ├── index.js

And so for each component. ExampleComponent.js and ExampleComponent.test.js do not raise questions for me, but index.js remains a mystery. Moreover, the file contains the same everywhere and looks like this: export { default } from './ExampleComponent';

What's the point?


For example, you have a customBtn folder inside with a customBtn.jsx file.

If you import the customBtn.jsx file from the components folder (without index.js), you will need to write like this.

import CustomBtn from "./components/customBtn/customBtn";

If you add index.js inside the customBtn folder, you won't have to write /customBtn/customBtn twice in a row

import CustomBtn from "./components/customBtn";

It is not necessary to write this way if you feel comfortable writing the folder and file names twice.

Scroll to Top