second-dehydrator
Version:
Dehydrate React/Preact components on the server so that they can be rehydrated with their original props on the client.
25 lines (20 loc) • 806 B
JavaScript
export default function hydrate (render, componentMap) {
Object.keys(componentMap).forEach(component => {
const loadComponent = componentMap[component]
const componentElements = [].slice.call(
document.querySelectorAll(`[data-component-name="${component}"]`)
)
loadComponent().then(maybeComponent => {
const Component = maybeComponent.default || maybeComponent
componentElements.forEach(el => hydrateComponent(Component, el))
})
})
function hydrateComponent (Component, componentEl) {
const componentDataId = componentEl.getAttribute('data-hydration-id')
const dataEl = document.querySelector(
`script[data-hydration-id="${componentDataId}"]`
)
const props = JSON.parse(dataEl.innerHTML)
render(Component, props, componentEl)
}
}