0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React入門】コンポーネントのインポートとエクスポート方法

Posted at

Reactにおけるコンポーネントのインポートとエクスポートについて、具体例を使って解説します。

Catコンポーネントの作成

まずは、Cat.jsxというファイルにCatコンポーネントを作成します。このファイルではJSX(JavaScript XML)を多用するため、拡張子は.jsxを使用します。

以下がそのCatコンポーネントです:

function Cat() {
  return (
    <div className="card">
      <h2>Mr. Whiskers</h2>
      <img
        src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/running-cats.jpg"
        alt="Cute cats running in the grass."
      />
    </div>
  );
}

エクスポートする方法

他のファイルでこのCatコンポーネントを使いたい場合は、まずエクスポートする必要があります。以下のようにexport defaultを使います:

function Cat() {
  return (
    <div className="card">
      <h2>Mr. Whiskers</h2>
      <img
        src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/running-cats.jpg"
        alt="Cute cats running in the grass."
      />
    </div>
  );
}

export default Cat;

または、関数の定義と同時にエクスポートすることもできます:

export default function Cat() {
  return (
    <div className="card">
      <h2>Mr. Whiskers</h2>
      <img
        src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/running-cats.jpg"
        alt="Cute cats running in the grass."
      />
    </div>
  );
}

AppコンポーネントでCatを使う

Reactプロジェクトには、通常App.jsxというルートコンポーネントがあります。ここにCatコンポーネントを読み込んで表示する方法を見てみましょう。

まずは、Catをインポートします:

import Cat from "./Cat";

そして、Appコンポーネントの中でCatを呼び出します:

import Cat from "./Cat";

export default function App() {
  return (
    <Cat />
  );
}

これで、Appコンポーネントを表示することで、Catコンポーネントも画面上にレンダリングされます。


まとめ

  • Reactでは、コンポーネントごとにファイルを分けて管理するのが一般的です。
  • 各コンポーネントはexport defaultで外部に公開し、必要な場所でimportして使います。
  • コンポーネントを組み合わせることで、柔軟で拡張性の高いUIを構築できます。

Reactプロジェクトを進める中で、こうしたモジュール化の考え方に慣れていくと、よりスケーラブルなアプリ開発が可能になります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?