1
0

【React】export と export default の違い

Posted at

export と export default の違い

Reactコンポーネントをエクスポートする場合、exportexport 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を使用します。ただし、どちらを使用しても機能的には同じです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0