Next.js ForwardRef Error in Storybook

In the process of doing a lazy loading run in Next.js1 with next/dynamic, I encountered this error.

Loading...
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `ForwardRef(LoadableComponent)`.

Bit weird, because I wasn't doing any specific ref passing, and it worked fine in dev and prod. Only Storybook (7) was having conniptions.

My syntax appeared fine (examples adapted from Next.js documentation):

Loading...
const DynamicHeader = dynamic(() => import('../components/header'));

Stumbled on this StackOverflow thread for a similar error: javascript Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object - Stack Overflow

The comments primarily discussed default vs destructured imports and it felt NQR because my components are only default exports, but decided to give the named export option a go anyway.

Loading...
const DynamicHeader = dynamic(() => import('../components/header').then((mod) => mod.default) );

Turns out that's what Storybook wanted. And it still works in dev and prod.

Haven't got time to figure out why it needed the specificity, but I'll go with it. Figure it's something to do with webpack.

May the odds be ever in your favour
May the odds be ever in your favour

Footnotes

  1. Optimizing: Lazy Loading | Next.js

Published May 7, 2024