I am trying to use dynamic import in NextJS and I do not understand why it works only while storing imported component in a variable. It breaks when I try to return it from other function.
It works this way:
import dynamic from "next/dynamic";
const Article = dynamic(() => import("tutorial/ru/welcome.mdx"));
but like this, well, it breaks:
import dynamic from "next/dynamic";
export default ({ route }) => {
switch (route) {
case "ru":
default:
return dynamic(() => import("tutorial/ru/welcome.mdx"));
}
};
I get the Invalid hook call. Hooks can only be called inside of the body of a function component message.
I found a solution to get over this issue!
import dynamic from "next/dynamic";
import Loader from "components/Loader/Loader";
import Error from "pages/_error";
export default ({ route }) => {
const Article = dynamic(
() => import(`tutorial/${route}.mdx`).catch(err => {
return () => <Error />
}),
{ loading: () => <Loader /> }
);
return <Article />
};
I should store the component in the variable after all, but I get the component itself dynamically using literal strings, and after that I return the component as tag (). Works fine now!