Skip to content

Instantly share code, notes, and snippets.

@ChaseH88
Created April 27, 2021 19:55
Show Gist options
  • Select an option

  • Save ChaseH88/10629fa51d2424fe179dcfb812419dba to your computer and use it in GitHub Desktop.

Select an option

Save ChaseH88/10629fa51d2424fe179dcfb812419dba to your computer and use it in GitHub Desktop.
Dynamic ReactComponent class to inject components into an existing DOM tree. An example use case would be to use this class when you are working with an app that isn't React first. NOTE: I also added Redux to this example to show how you can import your own libraries. This will be used on a page-by-page basis and the Redux store will not persist.
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { store } from 'Config/store'
interface ReactComponentOptions {
domID: string
[key: string]: any
}
class ReactComponent {
private app: any = null
private props: { [key: string]: any } = {}
private options: ReactComponentOptions;
/**
*
* @param App - React Component
* @param props - The props that should be given to the component
* @param options - Other options including the DOM ID in which to render. *Customizable*
*/
constructor(App: any, props = {}, options: ReactComponentOptions = { domID: 'app' }){
this.app = App;
this.props = props;
this.props = options;
this.listen()
}
/**
* Listen for the DOM's readyState to complete
* calls the render method
*/
private listen() {
if (document.readyState === 'complete') {
this.render(this.app)
} else {
document.addEventListener("DOMContentLoaded", () => {
this.render(this.app)
})
}
}
/**
* Method to render the React component to the DOM
* @param App
*/
private render(App: any) {
const dom = document.getElementById(this.options.domID);
const component = (
<Provider store={store}>
<App {...this.props} />
</Provider>
);
ReactDOM.render(component, dom)
}
}
export { ReactComponent }
/**
================= SEE BELOW FOR USAGE =================
*/
const MyComponent = () => (
<p>This is a component</p>
)
new ReactComponent(
MyComponent,
{
userid: '72nXjnPjn9i',
loggedIn: false
},
{
domID: 'myElementWithID'
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment