1

I have a large ReactJS class which I'd like to clone. The scenario is that the original React class is in one batch of code, which I want to largely re-use in another - just with a few small changes. Ideally I was hoping I could do something like this:

var Element1 = React.createClass({ 
  customMethod1: function() { ... },
  customMethod2: function() { ... },
  render: function () { ... }
});

// clone and override whatever we want
var Element2 = React.cloneClass(Component1);
Element2.customMethod1 = function () { ... };

// now we can use <Element2 />

Any idea?

benjamin.keen
  • 1,936
  • 1
  • 20
  • 29

1 Answers1

2

Try using composition over cloning/inheritance. This is recommended approach with React.

Starting from React 0.12 the new API introduced React.createFactory.

var MyComponentClass = React.createClass(...);

var MyComponent = React.createFactory(MyComponentClass);

var MyOtherComponent = React.createClass({
  render: function() {
    return MyComponent({ prop: 'value' });
  }
});

Another possible way of composition would be to pass react element into another component via refs: https://stackoverflow.com/a/25723635/540802

Community
  • 1
  • 1
Yevgen Safronov
  • 3,977
  • 1
  • 27
  • 38
  • Thanks, Eugene. Yes, I've been reading about how everyone recommends composition. Seems like there's numerous ways to tackle the problem, like the ones you pointed out. Coming from Backbone-land where it's easy to extend one View/Model into another, these other techniques require a bit of a mind-shift. Still not sure if they'll fit well yet... – benjamin.keen Apr 23 '15 at 21:34