Last active
June 4, 2017 20:04
-
-
Save wildlyinaccurate/12edf0a7372cd28ddd3883795022d791 to your computer and use it in GitHub Desktop.
Simplified approach for hydrating statically-rendered React components on the client.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import ReactDOM from 'react-dom' | |
const hydrateComponent = (scriptEl) => { | |
const componentId = scriptEl.getAttribute('data-hydration-data-id') | |
const componentElement = document.querySelector(`[data-hydration-component-id="${componentId}"]`) | |
const props = JSON.parse(scriptEl.innerHTML) | |
import(componentId).then(Component => ReactDOM.render(<Component {...props} />, componentElement)) | |
} | |
[].slice.call(document.querySelectorAll('[data-hydration-data-id]')).forEach(hydrateComponent) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import ReactDOMServer from 'react-dom/server' | |
export default function Hydrator (props) { | |
const Component = props.Component | |
const componentId = Component.displayName | |
delete props.Component | |
return ( | |
<div> | |
<div data-hydration-component-id={componentId}> | |
<Component {...props} /> | |
</div> | |
<script | |
data-hydration-data-id={componentId} | |
type="application/hydration-data" | |
dangerouslySetInnerHTML={{ __html: JSON.stringify(props) }} | |
> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment