I have the following project structure:
/app
/components
/TextInputs
SearchInput.js
TextInput.js
/Buttons
Button.js
CircleButton.js
/screens
...
/utils
...
/services
...
/theme
theme.js
I have seen people using index.js files for importing/exporting stuff, in order to clean all imports of the app.
Is this the main purpose of index.js? Is it a good practice to have a index.js per directory?
If you need to import multiple files from a folder like:
import {SearchInput} from './components/TextInputs/SearchInput'
import {TextInput} from './components/TextInputs/TextInput'
I would recommend creating an index file. This reduces the amount of import statements you are going to use in other components:
/app
/components
/TextInputs
SearchInput.js
TextInput.js
index.js
with the content: (/TextInputs/index.js)
import {SearchInput} from './SearchInput'
import {TextInput} from './TextInput'
export {SearchInput, TextInput}
and use it on the other components like:
import {TextInput, SearchInput} from './components/TextInputs'
This is why the index.js is used mostly, and makes the imports more managable and readable for some cases. Entirely up to developer!
It's likely more personal preference than not, but I think indexes has 2 main benefits.
// ./src/example/index.js
import Example from './src/example'
...
// ./theme/index.scss
import './theme'
Which will automatically import the index.
This also helps a lot when you're using something like css modules or styles per component where it's stored in the same directory, so that you can still import the normal component without having to do something like import Header from './Header/header.js'.
There is a caveat though, while it serves some benefits it can also be difficult to debug sometimes when you have 20 files called index, when one of them breaks and the debugger is only telling you it's in a file called "index.js" without being more specific about which file or what directory.