DEV Community

Aravind Balla
Aravind Balla

Posted on • Originally published at Medium on

2 1

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.

class WelcomeComp extends React.Component {
constructor(props) {
super(props);
this.state = { name: '' }
if (props.name) this.state = { name: props.name };
}
updateName = name => this.setState({ name })
render() {
return (
<p>I am a React Component. Hello {this.state.name}</p>
)
}
}
// This is a compiled(transpiled) version of the above code, which you actually go into the HTML.
/*
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var WelcomeComp = function (_React$Component) {
_inherits(WelcomeComp, _React$Component);
function WelcomeComp(props) {
_classCallCheck(this, WelcomeComp);
var _this = _possibleConstructorReturn(this, (WelcomeComp.__proto__ || Object.getPrototypeOf(WelcomeComp)).call(this, props));
_this.updateName = function (name) {
return _this.setState({ name: name });
};
_this.state = { name: '' };
if (props.name) _this.state = { name: props.name };
return _this;
}
_createClass(WelcomeComp, [{
key: 'render',
value: function render() {
return React.createElement(
'p',
null,
'I am a React Component. Hello ',
this.state.name
);
}
}]);
return WelcomeComp;
}(React.Component);
*/
view raw WelcomeComp.js hosted with ❤ by GitHub

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay