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
- One component per file: Makes exports more straightforward
- Consistent naming: Match component name to file name
Button.js
should exportButton
- 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
- Forgetting any export:
function Component() {...}
// Missing export!
- Mixing up export types:
// Component.js
export default function Component() {...}
// AnotherFile.js
import { Component } from './Component'; // Wrong - should be default import
- Typos in export names:
function MyComponent() {...}
export default Mycomponent; // Typo in name
Debugging Tips
If you get “import/no-unresolved” or similar errors:
- Check the file has an export
- Verify the import path is correct
- Ensure the export type (default/named) matches the import style
- Check for typos in component names