Created
August 13, 2016 15:31
-
-
Save gauravtiwari/ecd92ec5506199f9ad4ef34801591d54 to your computer and use it in GitHub Desktop.
A dynamic react relay component renderer
This file contains 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
/* | |
Mount and Unmount react components at nodes | |
*/ | |
/* global Turbolinks, ReactHelper */ | |
import ReactDOM from 'react-dom'; | |
import Relay from 'react-relay'; | |
import React from 'react'; | |
// Notification components | |
import LoadingComponent from './react/components/shared/loadingComponent'; | |
import ErrorComponent from './react/components/shared/errorComponent'; | |
// UnMount components from Nodes | |
function unmountComponents() { | |
const nodes = document.getElementsByClassName('react-component'); | |
for (let i = 0; i < nodes.length; ++i) { | |
const node = nodes[i]; | |
ReactDOM.unmountComponentAtNode( | |
document.getElementById(node.getAttribute('id')) | |
); | |
} | |
} | |
// Mount components at Nodes | |
function mountComponents() { | |
const nodes = document.getElementsByClassName('react-component'); | |
for (let i = 0; i < nodes.length; ++i) { | |
const node = nodes[i]; | |
const componentName = node.getAttribute('data-component-name'); | |
const domNodeId = node.getAttribute('id'); | |
const routeName = node.getAttribute('data-component-route'); | |
// Get the Component and Route Object | |
const { component } = ReactHelper.getComponent(componentName); | |
const { route } = ReactHelper.getRoute(routeName); | |
// Mount the root component to domNodeId | |
ReactDOM.render( | |
<Relay.Renderer | |
Container={component} | |
queryConfig={route} | |
environment={Relay.Store} | |
render={({ props, error, retry }) => { | |
if (props) { | |
return ( | |
React.createElement(component, props) | |
); | |
} else if (error) { | |
return <ErrorComponent retry={retry} />; | |
} | |
return <LoadingComponent />; | |
}} | |
/>, | |
document.getElementById(domNodeId) | |
); | |
} | |
} | |
// Listen DOM events and { Mount, Unmount } react components | |
export default function renderComponents() { | |
document.addEventListener('DOMContentLoaded', () => { | |
if (!(typeof Turbolinks.controller !== 'undefined')) { | |
mountComponents(); | |
} else { | |
document.addEventListener('turbolinks:before-cache', unmountComponents); | |
document.addEventListener('turbolinks:load', mountComponents); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment