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

More than 1 year has passed since last update.

React RouterでReact.lazyした時のエラー

Posted at

React Router v6 のチュートリアルを参考に実装していくと、buildした際にindex.jsのファイルサイズが大きくなります。対策のため、各コンポーネントをdynamic importにしました。

main.jsx
import React, {lazy} from 'react'
import ReactDOM from 'react-dom/client'
import {
    createRoutesFromElements,
    createBrowserRouter,
    RouterProvider,
    Route,
} from "react-router-dom";
const Index = lazy(() => import('./routes/Index'));
const Root = lazy(() => import('./routes/Root'));
const Hoge = lazy(() => import('./routes/Hoge'));

const router = createBrowserRouter(
    createRoutesFromElements(
        <Route path="/" element={<Root />} >
            <Route>
                <Route index element={<Index />} />
                <Route path="hoge" element={<Hoge />} />
            </Route>
        </Route>
    )
);

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>,
)

上記のようにReact.lazyを使用したところ、画面遷移時にエラーになりました。

Oops!
Sorry, an unexpected error has occurred.

A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition.

解決法

修正前.jsx
<div>
  <Outlet />
</div>
修正後.jsx
<Suspense fallback={<div>Loading...</div>}>
  <Outlet />
</Suspense>

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?