1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

React importとexport

1
Last updated at Posted at 2023-10-17

importとexportについて

他のファイルに記述されているライブラリやコンポーネントを利用するためのimportと,他のファイルから利用できるようにするexportの記述方法についてまとめる.

import:使う側

ライブラリや別のファイルで記述したコンポーネントを利用するための,いくつかの基本的なimport方法をまとめる.

Reactライブラリ

import React from 'react';

Reactのコンポーネントを書く場合は必ず必要.

ReactDOMライブラリ

import ReactDom from 'react-dom';

Reactの仮想DOMをブラウザのリアルDOMに反映させる(つまり,HTMLにReactのコンポーネントを反映させる)ライブラリ.
基本的には,HTMLから参照されるjsファイルやjsxファイルにだけ記述すれば良い.

コンポーネント

import ComponentName from "componentsPath";
//または
import { ComponentName, ComponentName2 } from "componentsPath";

基本的には,import [importするコンポーネント名] from [importするファイルのパス]という形になる.

中括弧の有無について

importするコンポーネント名を中括弧で囲む場合がある.コンポーネントのエクスポート方法にはデフォルトエクスポートと名前付きエクスポートの2つの方法があり,それによって中括弧の有無が決まる

  • デフォルトエクスポート:中括弧なし
  • 名前付きエクスポート:中括弧あり

別名でimportする方法

import * as name from 'componentPath';
import A as B from 'componentPath';

コンポーネントファイルの全体を別名でインポートする場合:* as name
コンポーネントファイルの一部を別名でインポートする場合:A as B

export:使われる側

作成したコンポーネントをエクスポートすることで,別のファイルから利用できるようにする.
エクスポート方法については,名前なしと名前ありエクスポートの2種類がある.

Defaultエクスポート(名前なし)

function ComponentName() {
	//コンポーネントの定義
}
export default ComponentName;

または

export default function ComponentName() {
	//コンポーネントの定義
}

exportの後ろでdefaultをつけることでエクスポートする.コンポーネントのファイルに複数のコンポーネントを定義することができるが,デフォルトエクスポートできるのは1つだけである.

Namedエクスポート(名前あり)

function ComponentName() {
	//コンポーネントの定義
}

function ConponentName2(){
	//コンポーネントの定義
}

export { ComponentName, ComponentName2 };

または

export function ComponentName() {
	//コンポーネントの定義
}
export function ConponentName2(){
	//コンポーネントの定義
}

Namedエクスポートはdefaultをつけずにexportする.
デフォルトエクスポートは1つだけだが,この場合は複数をエクスポートすることができる.

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?