Forgetting to export a component from its file

Loading

Forgetting to Export a Component

A common React mistake is creating a component but forgetting to export it from its file, resulting in errors when trying to import and use it elsewhere.

The Problem

You’ve created a component but can’t import it because it wasn’t exported:

// ❌ In Button.js
function Button() {
  return <button>Click me</button>;
}
// Missing export statement!

// ❌ In another file
import Button from './Button'; // Error: No default export found

Solutions

1. Default Export (for primary component)

// ✅ In Button.js
function Button() {
  return <button>Click me</button>;
}

export default Button; // Add this line

// ✅ In another file
import Button from './Button'; // Now works

2. Named Export (for multiple components)

// ✅ In buttons.js
export function PrimaryButton() {
  return <button className="primary">Submit</button>;
}

export function SecondaryButton() {
  return <button className="secondary">Cancel</button>;
}

// ✅ In another file
import { PrimaryButton, SecondaryButton } from './buttons';

3. Combined Exports

// ✅ In form-components.js
function Input() { /* ... */ }
function TextArea() { /* ... */ }

export {
  Input as default, // Default export
  TextArea         // Named export
};

// ✅ In another file
import Input, { TextArea } from './form-components';

Best Practices

  1. One component per file: Makes exports more straightforward
  2. Consistent naming: Match component name to file name
  • Button.js should export Button
  1. Use index files: For cleaner imports from directories
   // components/index.js
   export { default as Button } from './Button';
   export { default as Input } from './Input';

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

Common Mistakes

  1. Forgetting any export:
   function Component() {...}
   // Missing export!
  1. Mixing up export types:
   // Component.js
   export default function Component() {...}

   // AnotherFile.js
   import { Component } from './Component'; // Wrong - should be default import
  1. Typos in export names:
   function MyComponent() {...}
   export default Mycomponent; // Typo in name

Debugging Tips

If you get “import/no-unresolved” or similar errors:

  1. Check the file has an export
  2. Verify the import path is correct
  3. Ensure the export type (default/named) matches the import style
  4. Check for typos in component names

Leave a Reply

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