Skip to content

Instantly share code, notes, and snippets.

@strzibny
Forked from chadwilken/react-controller.js
Created October 25, 2020 15:26
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 strzibny/65cd77c5bf449aba973d1f554de0236e to your computer and use it in GitHub Desktop.
Save strzibny/65cd77c5bf449aba973d1f554de0236e to your computer and use it in GitHub Desktop.
import { Controller } from 'stimulus';
import React from 'react';
import ReactDOM from 'react-dom';
import AppContainer from 'components/core/AppContainer';
export default class extends Controller {
connect() {
const Component = window.ReactComponents[this.data.get('component')];
let props = this.data.get('props') || {};
if (typeof props === 'string') {
props = JSON.parse(props);
}
ReactDOM.render(
<AppContainer>
<Component { ...props } />
</AppContainer>,
this.element,
);
document.addEventListener('turbolinks:before-cache', this.unmountComponent);
}
disconnect() {
document.removeEventListener('turbolinks:before-cache', this.unmountComponent);
}
unmountComponent = () => {
ReactDOM.unmountComponentAtNode(this.element);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment