Forgetting to export a component from its file

Loading

Handling Missing Component Exports in React

A common mistake in React development is forgetting to export a component from its file, which leads to “Component not found” errors when trying to import it elsewhere. Here’s how to properly handle component exports:

The Problem

File: Button.js

// Component is defined but not exported
const Button = ({ children }) => {
  return <button>{children}</button>;
}

File: App.js

import Button from './Button'; // Error: Cannot find module

Solutions

1. Default Export (Single Component Per File)

const Button = ({ children }) => {
  return <button>{children}</button>;
}

export default Button; // Proper default export

2. Named Export (Multiple Components Per File)

export const Button = ({ children }) => {
  return <button>{children}</button>;
}

export const SubmitButton = () => {
  return <Button>Submit</Button>;
}

3. Combined Export Approach

const Button = ({ children }) => {
  return <button>{children}</button>;
}

const SubmitButton = () => {
  return <Button>Submit</Button>;
}

export { Button as default, SubmitButton }; // Default + named

Best Practices

  1. Be consistent with your export style throughout the project
  2. Use named exports for utility components or hooks
  3. Prefer default exports for main components
  4. Use clear names that match the file name
// File: PrimaryButton.js
const PrimaryButton = () => {...};
export default PrimaryButton; // Matches file name

Common Patterns

1. Export Immediately

// Option 1: Default export
export default function Button() {
  return <button>Click</button>;
}

// Option 2: Named export
export function Button() {
  return <button>Click</button>;
}

2. Barrel Files (index.js)

// In components/Button/index.js
export { default } from './Button';
export { default as ButtonGroup } from './ButtonGroup';

Debugging Tips

  1. Check the import path is correct
  2. Verify the export exists in the source file
  3. Look for typos in component names
  4. Restart your dev server after adding exports

Advanced Patterns

1. Dynamic Exports

const components = {
  Button,
  Input,
  Card
};

export default components;

2. Higher-Order Components

function withStyle(Component) {
  return (props) => <Component {...props} className="styled" />;
}

export default withStyle(Button);

Leave a Reply

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