Skip to content

Commit bed32bc

Browse files
committed
resolve react.lazy elements
1 parent 86e9663 commit bed32bc

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

  • packages/@headlessui-react/src/utils

packages/@headlessui-react/src/utils/render.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,11 @@ function _render<TTag extends ElementType, TSlot>(
148148
| ReactElement
149149
| ReactElement[]
150150

151+
// Unwrap `react.lazy` wrappers when the payload has already been fulfilled.
152+
// This can happen with e.g. Next.js client-side navigations where the child
153+
// element is wrapped in a lazy boundary from React Server Components.
154+
resolvedChildren = resolveLazyElement(resolvedChildren)
155+
151156
// Allow for className to be a function with the slot as the contents
152157
if ('className' in rest && rest.className && typeof rest.className === 'function') {
153158
rest.className = rest.className(slot)
@@ -467,6 +472,23 @@ function getElementRef(element: React.ReactElement) {
467472
return React.version.split('.')[0] >= '19' ? element.props.ref : element.ref
468473
}
469474

475+
/**
476+
* Resolve a `react.lazy` wrapper to the underlying element when the lazy
477+
* payload has already been fulfilled. This handles the case where frameworks
478+
* like Next.js wrap elements in lazy boundaries (e.g. during client-side
479+
* navigation with React Server Components). If the payload isn't resolved
480+
* yet, the original value is returned as-is.
481+
*/
482+
function resolveLazyElement(element: any): any {
483+
if (element != null && element.$$typeof === Symbol.for('react.lazy')) {
484+
let payload = element._payload
485+
if (payload != null && payload.status === 'fulfilled') {
486+
return resolveLazyElement(payload.value)
487+
}
488+
}
489+
return element
490+
}
491+
470492
export function isFragment(element: any): element is typeof Fragment {
471493
return element === Fragment || element === Symbol.for('react.fragment')
472494
}

0 commit comments

Comments
 (0)