Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.