Handling Multiple Default Exports in a Single File
Having multiple default exports in one file is invalid JavaScript syntax and will cause errors. Here’s how to properly structure your exports:
The Problem
Invalid code:
// components.js
const Button = () => <button>Click</button>;
export default Button;
const Card = () => <div className="card"></div>;
export default Card; // SyntaxError: Duplicate export of 'default'
Correct Solutions
1. Single Default Export (Recommended)
// components.js
const Button = () => <button>Click</button>;
const Card = () => <div className="card"></div>;
// Export as named exports
export { Button, Card };
// OR export one as default
export default Button;
export { Card }; // named export
2. Multiple Components in One File
// Button.js
const Button = () => <button>Click</button>;
export default Button;
// Card.js
const Card = () => <div className="card"></div>;
export default Card;
3. Object Export Pattern
// components.js
const Button = () => <button>Click</button>;
const Card = () => <div className="card"></div>;
export default {
Button,
Card
};
// Import usage:
import components from './components';
const { Button, Card } = components;
Best Practices
- One default export per file – Follows standard conventions
- Use named exports for multiple components
- Split components into separate files – Better for code organization
- Be consistent across your project
Common Patterns
1. Component + Styles Export
// Button.js
export const ButtonStyles = { color: 'blue' };
const Button = () => <button style={ButtonStyles}>Click</button>;
export default Button;
2. Main Component + Subcomponents
// Card.js
export const CardHeader = () => <div className="header"></div>;
export const CardBody = () => <div className="body"></div>;
const Card = () => (
<div className="card">
<CardHeader />
<CardBody />
</div>
);
export default Card;
TypeScript Considerations
TypeScript will enforce single default exports more strictly. The same patterns apply but with type annotations:
// components.tsx
interface ButtonProps {
text: string;
}
const Button: React.FC<ButtonProps> = ({ text }) => <button>{text}</button>;
export default Button;
Migration Strategy
If refactoring existing code with multiple default exports:
- Identify all default exports in the file
- Convert all but one to named exports
- Update all import statements in other files
- Consider splitting into multiple files if components are large