Export Patterns for Multiple Components
What you'll learn: How to cleanly export multiple related components from a single file without making imports messy.
When you have a file containing multiple components (like a main component and its helper components), you need a clear strategy for making them available to other files.
Named Exports for Multiple Components
The simplest pattern is using named exports for each component:
// Button.jsx
export function PrimaryButton() {
return <button className="primary">Click me</button>;
}
export function SecondaryButton() {
return <button className="secondary">Cancel</button>;
}
export function IconButton() {
return <button className="icon">🔔</button>;
}
Now other files can import exactly what they need:
import { PrimaryButton, SecondaryButton } from './Button';
Barrel Exports
For better organization, you can collect all exports at the bottom of the file:
// Button.jsx
function PrimaryButton() {
return <button className="primary">Click me</button>;
}
function SecondaryButton() {
return <button className="secondary">Cancel</button>;
}
function IconButton() {
return <button className="icon">🔔</button>;
}
// Barrel export
export { PrimaryButton, SecondaryButton, IconButton };
This "barrel" pattern makes it obvious what's public vs. internal to the file. Think of it like a store's front counter — everything behind it exists, but only items on the counter are for sale.
You can even create a main component with a default export alongside named exports:
export default function Button() {
return <button>Default Button</button>;
}
export { PrimaryButton, SecondaryButton };
Key Takeaway: Use named exports for multiple components in one file, and consider barrel exports at the bottom to clearly declare your file's public API.