DEV Community

Aravind Balla
Aravind Balla

Posted on • Originally published at Medium on

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 commented 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.

<html>

<head>
<title>Sandbox</title>
<meta charset="UTF-8" />
<script src="<https://unpkg.com/react/umd/react.production.min.js>"></script>
<script src="<https://unpkg.com/react-dom/umd/react-dom.production.min.js>"></script>
</head>

<body>
<div id="app"></div>
<div id="root"></div>

<script src="build/existing.js"></script>
<script src="build/WelcomeComp.js"></script>
<script type="text/javascript">
  var rootEl = document.getElementById('root');
          ReactDOM.render(
    React.createElement(WelcomeComp, null, null),
    rootEl
  );
        </script>
</body>

</html>

This would mount the component to the root div. Remember you cannot use JSX here as the script in HTML has a type text/javascript. So we used React.createElement() instead of .

The issue

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.

<script type="text/javascript">
var rootEl = document.getElementById('root');
var componentProps = {
name: 'Balla',
ref: function (ref) {
this.welcomeComp = ref;
}
};
ReactDOM.render(
  React.createElement(WelcomeComp, componentProps, null),
  rootEl
);

setTimeout(function () {
this.welcomeComp.updateName('Aravind')
}, 2000);
</script>

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!

References

Top comments (0)