Creating & Managing components outside React
You are probably not starting a new project with React in the frontend. You just want to build some components, make use of the apis that your frontend already consumes and use them in your existing application.
Awesome! You can always do that. Let me outline the workflow here.
Take the built output js file and include it your HTML(application). You would need to add React and ReactDOM to the HTML to mount the components on to the page.
The transpiled version of the above code is most probably the output you would be getting from build system. (Webpack isn’t mandatory. You can use gulp or grunt if you development is setup using them.)
Next up is including things in your application. I am including directly into HTML.
This would mount the component to the root div. Remember you cannot use JSX here as the script in HTML has a type
React.createElement() instead of
But how would your Component communicate with the existing application? You could be fetching and sending requests from the component itself. Which would need some React code, that isn’t an issue. But in some cases, you need the component to sync up with existing stores in your application.
Maybe you have an ExtJS store or a RxJS store, maybe a MobX one. How do you sync the component with it? 🤔
React ref to our rescue
You can pass a reference to the component and store it as a local variable in the code. All the methods in the React Component can be accessed through those refs. Don’t quite get it? Here is the code.
Syncing is easy now. When ever there is an update, you can just call a method that changes the Component state. See how I did it in a timeout. You can even pass methods that update the store, in the props, and make the Component call it whenever it has to update.
Keep on hacking!
By Aravind Balla who is a friendly human, building things for himself, and sometimes for others. You should hit him up on Twitter!