Forgetting to export a component from its file

Loading

A common React mistake is creating a component but forgetting to export it, making it unavailable for use in other files. Here’s how to properly handle component exports:

The Problem

// MyComponent.js
function MyComponent() {  // ❌ No export statement
  return <div>Hello World</div>;
}

// App.js
import MyComponent from './MyComponent';  // Error: No default export

Solutions

1. Default Export (Single Component Files)

// MyComponent.js
export default function MyComponent() {  // ✅ Correct
  return <div>Hello World</div>;
}

// App.js
import MyComponent from './MyComponent';  // Works!

2. Named Export (Multiple Components/Utilities)

// components.js
export function Button() { /* ... */ }  // ✅ Named export
export function Input() { /* ... */ }

// App.js
import { Button, Input } from './components';

3. Mixed Exports (Default + Named)

// FormComponents.js
export default function Form() { /* ... */ }  // Default export
export function FormField() { /* ... */ }    // Named export

// App.js
import Form, { FormField } from './FormComponents';

Best Practices

  1. One component per file – Makes default exports straightforward
  2. Consistent naming – Match component name to file name
   MyComponent.js → export default function MyComponent()
  1. Use named exports for utility functions/hooks in same file
  2. Barrel files for organizing multiple components
   // components/index.js
   export { default as Button } from './Button';
   export { default as Card } from './Card';

Common Mistakes

  1. Forgetting export keyword
   function MyComponent() {...}  // ❌ Missing export
  1. Mixing up import types
   // Component.js
   export function MyComponent() {...}  // Named export

   // App.js
   import MyComponent from './Component';  // ❌ Should be { MyComponent }
  1. Default export naming mismatch
   // MyComponent.js
   export default function Foo() {...}  // ❌ Unexpected name

   // App.js
   import MyComponent from './MyComponent';  // Actually imports Foo

Auto-Fix Tools

  1. ESLint Rule: Enable import/no-unused-modules
  2. VS Code will show import errors for missing exports
  3. TypeScript will flag missing exports at compile time

Advanced Patterns

1. Dynamic Exports

// components/index.js
const components = {
  Button: () => {...},
  Input: () => {...}
};

export default components;

2. Forwarding Exports

// DesignSystem.js
export { Button } from './Button';
export { Input } from './Input';

Remember: Always verify your component is properly exported by trying to import it in another file during development.

Leave a Reply

Your email address will not be published. Required fields are marked *