Skip to content

Instantly share code, notes, and snippets.

@wildlyinaccurate
Last active June 4, 2017 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wildlyinaccurate/12edf0a7372cd28ddd3883795022d791 to your computer and use it in GitHub Desktop.
Save wildlyinaccurate/12edf0a7372cd28ddd3883795022d791 to your computer and use it in GitHub Desktop.
Simplified approach for hydrating statically-rendered React components on the client.
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)
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