Why This Happens

When working on big React projects, you should organize your components into folders. But importing those components can get messy. That’s where index.js comes in.

What’s Going On

In JavaScript (and React), if you import from a folder without specifying a file, it looks for the index.js file in that folder.

This makes index.js act like a default entry point for the directory, so you can re-export components and simplify import paths.

Solution

Folder Structure:

We have a Button component in its own folder. This is a common practice to keep files modular.

/components  /Button

    Button.js

    index.js

In Button.js:

This is your main React component, a simple button that renders on the UI. It’s exported as default.

const Button = () => {  return <button>Click me</button>;

};

 

export default Button;

In index.js:

Here you’re re-exporting the default export from Button.js. This line means: “When someone imports from this folder, give them Button.js.”

export { default } from ‘./Button’;

Now You Can Import Like This:

import Button from ‘./components/Button/Button’;

You can write:

import Button from ‘./components/Button’;

This shortens imports, makes it more readable and easier to scale and maintain.

Also Read: ReactJS Material Design

Bonus Tip:

You can use index.js to export multiple components from a directory too:

Let’s say your /components folder has multiple component directories like Button and Input. You can create a single index.js in /components to bundle them:

export { default as Button } from ‘./Button’;export { default as Input } from ‘./Input’;

Now import them like:

import { Button, Input } from ‘./components’;

No need to import each component individually from its folder.

Conclusion

  • index.js files help simplify imports and organize code better.
  • They’re automatically picked up when importing a folder.
  • Great for clean, readable, and scalable React apps.