LoginSignup
1
4

More than 1 year has passed since last update.

React.lazy()を使った条件分岐でコンポーネントを表示する方法

Last updated at Posted at 2022-03-06

やりたいこと

条件分岐でコンポーネントを表示させたい!
React.lazy()を使ってみる。React.lazyは動的にコンポーネントをimportすることができる。

下記の記事をためしてみた。

React.lazyの基本

Acomponent.jsxとBcomponent.jsxを用意

Acomponent.jsx

import React from "react";

export default Acomponent = () => {
  console.log("Acomponent");
  return <h1>A</h1>;
};

Bcomponent.jsx

import React from "react";

export default Bcomponent = () => {
  console.log("Bcomponent");
  return <h1>B</h1>;
};

普通にコンポーネントを使う場合

App.jsx

import React from "react";
import Acomponent from "./Acomponent";
import Bcomponent from "./Bcomponent";

export default function App() {
  return (
    <div>
      <h1>import component usual</h1>
      <Acomponent />
      <Bcomponent />
    </div>
  );
}

React.lazy()を使ったコンポーネントの使用

AcomponentとBcomponentが読み込みに時間がかかるとする。
React.lazy()を使うと、読み込み中はSuspenseのfallbackに指定した要素が表示され、読み込みが終わるとコンポーネントが表示される。このとき、AcomponentとBcomponentの両方が読み込み終わってから表示される。
React.lazy()の使う場合は、読み込むコンポーネントはdefault exportされたコンポーネントでないといけない。また、Suspenseで囲まれてないといけない。fallbackには文字列以外にもjsxがつかえる。

App.jsx

import React, { Suspense } from "react";
export default function App() {
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

  const AcompLazy = React.lazy(() =>
    sleep(1000).then(() => import("./Acomponent"))
  );
  const BcompLazy = React.lazy(() =>
    sleep(2000).then(() => import("./Bcomponent"))
  );

  return (
    <div>
      <h1>Test React.lazy()</h1>
      <Suspense fallback="loading...">
        <AcompLazy />
        <BcompLazy />
      </Suspense>
    </div>
  );
}

条件で表示させるコンポーネントを選択

isAやisBがtrueのときにコンポーネントを表示させるコード。
下記のようにコーディングするとtrue以外のコンポーネントは読み込まれない。

import React, { Suspense, useState } from "react";

export default function App() {
  const [isA, setIsA] = useState(false);
  const [isB, setIsB] = useState(true);

  const ViewComp = React.lazy(() => {
    if (isA) return import("./Acomponent");
    if (isB) return import("./Bcomponent");
    return import("./Ccomponent");
  });

  const fallback = <h1 style={{ color: "red" }}>Loading ...</h1>;

  return (
    <div>
      <h1>Test React.lazy()</h1>
      <Suspense fallback={fallback}>
        <ViewComp />
      </Suspense>
    </div>
  );
}
1
4
1

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
4