Skip to content

Instantly share code, notes, and snippets.

@gauravtiwari
Created August 13, 2016 15:31
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 gauravtiwari/ecd92ec5506199f9ad4ef34801591d54 to your computer and use it in GitHub Desktop.
Save gauravtiwari/ecd92ec5506199f9ad4ef34801591d54 to your computer and use it in GitHub Desktop.
A dynamic react relay component renderer
/*
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