Skip to content

Commit

Permalink
Mark printed elements by portal head, but it does double print
Browse files Browse the repository at this point in the history
  • Loading branch information
dac09 committed Aug 8, 2023
1 parent 0973ace commit c66f7e1
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions packages/web/src/components/PortalHead.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,34 @@ import { createPortal } from 'react-dom'

import { useServerInsertedHTML } from './ServerInject'

function addDataAttributeMarker(children: React.ReactNode) {
return React.Children.toArray(children).map((child, i) => {
return React.cloneElement(child as React.ReactElement, {
'data-rwjs-head': true,
key: 'data-rwjs-head-' + i,
})
})
}

const PortalHead: React.FC<React.PropsWithChildren> = ({ children }) => {
const findableChildren = addDataAttributeMarker(children)

useServerInsertedHTML(() => {
// Add "data-rwjs-head" attribute to anything inside <PortalHead>,
// This is then later moved to the <head> in the final block of the transform stream (see streamHelpers.ts)
return React.Children.toArray(children).map((child, index) => {
return React.cloneElement(child as React.ReactElement, {
'data-rwjs-head': `bazinga-${index}`,
})
})
return findableChildren
})

if (typeof window === 'undefined') {
// Don't do anything on the server, handled by above callback
return null
} else {
return createPortal(<>{children}</>, document.head)
//@TODO HALP These get rendered twice even with the same key, after the React bundle loads
// but we can't remove this because neeeded for client side nav/render
// Portals must work differently to standard react diffing.

// Logic needs to be something like: if (clientSideRouting) { return createPortal } else { return null }
return createPortal(findableChildren, document.head)
}
}

Expand Down

0 comments on commit c66f7e1

Please sign in to comment.