export と export default の違い
Reactコンポーネントをエクスポートする場合、export
とexport default
の2つの方法があります。これらの違いは以下の通りです。
1. export : export文は、コンポーネントを名前付きエクスポートします。名前付きエクスポートを行うため、インポートする際には波括弧 {} を使用して、エクスポートされたコンポーネントの名前を指定する必要があります。
// MyComponent.js
export const MyComponent = () => {
return <div>Hello, World!</div>;
};
// 別のファイルでのインポート
import { MyComponent } from './MyComponent';
2. export default : export default
文は、コンポーネントをデフォルトエクスポートします。デフォルトエクスポートされたコンポーネントは、インポートする際に任意の名前を使用することができます。名前がなく、ファイル全体から1つのエクスポートだけを行いたい場合に便利です。
// MyComponent.js
const MyComponent = () => {
return <div>Hello, World!</div>;
};
export default MyComponent;
// 別のファイルでのインポート
import MyComponent from './MyComponent';
通常、コンポーネントが1つしかない場合はexport default
を使用し、複数のコンポーネントをエクスポートする場合はexport
を使用します。ただし、どちらを使用しても機能的には同じです。