Search code examples
javascriptclassreactjsjavascript-objectsecmascript-6

React components as plain JS objects?


Does anybody has experience in working with React components as plain JS objects instead of annoying ES6 classes and deprecated .createClass method.

Maybe you have some examples of factory functions or similar to share?

Thanks!


Solution

  • React.Component is a plain javascript function, since es6 classes are syntactic sugar around them. So we could use whatever es5 class-like concept we like e.g. I just borrowed Backbone's extend method here:

    // From backbone
    var extend = function(protoProps) {
        var parent = this;
        var child;
    
        var extendObj = function(obj1, obj2) {
           for (var i in obj1) {
              if (obj1.hasOwnProperty(i)) {
                 obj2[i] = obj1[i];
              }
           }
        };
    
        // The constructor function for the new subclass is either defined by you
        // (the "constructor" property in your `extend` definition), or defaulted
        // by us to simply call the parent constructor.
        if (protoProps && hasOwnProperty.call(protoProps, 'constructor')) {
          child = protoProps.constructor;
        } else {
          child = function() { return parent.apply(this, arguments); };
        }
    
        // Set the prototype chain to inherit from `parent`, without calling
        // `parent` constructor function.
        var Surrogate = function(){ this.constructor = child; };
        Surrogate.prototype = parent.prototype;
        child.prototype = new Surrogate;
    
        // Add prototype properties (instance properties) to the subclass,
        // if supplied.
        if (protoProps) extendObj(child.prototype, protoProps);
    
        // Set a convenience property in case the parent's prototype is needed
        // later.
        child.__super__ = parent.prototype;
    
        return child;
    };
    
    React.Component.extend = extend;
    

    Then we could create components like this:

    var MyComponent = React.Component.extend({
        constructor: function() {
            console.log('hello from react component');
    
            this.state = {
                open: false
            };
    
            React.Component.apply(this, arguments);
        }
    });
    
    new MyComponent();
    

    That's just an example (and untested), you could do any kind of prototypal implementation you like since it's just a normal function. If you search for "es5 inheritance" you should be able to apply any of those solutions.