Reputation: 6121
I have a next.js page with dynamic imports, which worked well until now, but since I started using the custom loading components I get the warning
Warning: Expected server HTML to contain a matching <em> in <div>.
What can I do to avoid this warning ?
// pages/index.tsx:
import React from 'react';
import dynamic from 'next/dynamic';
import { LoadingComponent } from '../src/LoadingComponent';
// -- The custom loading fallback component
const loadingFallback = { loading: LoadingComponent };
// -- The dynamically loaded component
const DynamicallyLoadedComponent = dynamic(
() => import('../src/DynamicallyLoadedComponent'),
loadingFallback
);
// -- The main component
function Main(){
return <DynamicallyLoadedComponent />;
}
export default Main;
// src/DynamicallyLoadedComponent.tsx:
export default function DynamicallyLoadedComponent(){
return <div>ready loaded, final page content.</div>;
};
// src/LoadingComponent.tsx:
export const LoadingComponent = () => {
return <em>... loading ...</em>;
}
Upvotes: 0
Views: 1633
Reputation: 6121
Apparently you can not extract the part { loading: LoadingComponent }
into a variable, so it has to be written
inline, e.g.:
const DynamicallyLoadedComponent = dynamic(
() => import('../src/DynamicallyLoadedComponent'),
{ loading: LoadingComponent } // <-- needs to be written like this, a variable can't be used
);
Maybe this is because Next.js analyses the code in a kind of "pre-compiling" step and expects to find exactly this pattern (?).
Probably this is the same requirement as mentioned under Basic usage regarding the dynamic import itself:
Note: In
import('path/to/component')
, the path must be explicitly written. It can't be a template string nor a variable. Furthermore theimport()
has to be inside thedynamic()
call for Next.js to be able to match webpack bundles / module ids to the specificdynamic()
call and preload them before rendering.
dynamic()
can't be used inside of React rendering as it needs to be marked in the top level of the module for preloading to work, similar toReact.lazy
.
Upvotes: 2