second-dehydrator
Version:
Dehydrate React/Preact components on the server so that they can be rehydrated with their original props on the client.
27 lines (22 loc) • 918 B
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = hydrate;
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);
}
}
module.exports = exports['default'];