Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding a React Component Method

I'm using a library. This library creates a React Component, let's call it LibraryComponent.

I want to modify the functionality of one of this component methods, in particular handleDrag().

So I create my ExtendedLibrary module with the following code:

var LibraryComponent = require('libraryComponent');

LibraryComponent.prototype.handleDrag = function() {
    console.log("I'm the NEW handleDrag method.");
}
LibraryComponent.prototype.render = function() {
    console.log("I'm the NEW render method.");
}
module.exports = LibraryComponent;

As I understand changing the prototype of a creator object should change all its instances __proto__ atribute.

Into my mounted LibraryComponent, If I access:

this.__proto__.handleDrag() //I'm the NEW handleDrag method.
this.handleDrag() //I'm the OLD handleDrag method.

Why?

By contrast:

this.prototype.render() //I'm the NEW render method.
this.render() //I'm the NEW render method. (Accessing the __proto__ method too).

How can I do to override handleDrag definitely?

I tryied with class ExtendedLibrary extends LibraryComponent {...} too and the problem is the same (But I prefer not to include ES6 at all in my project.)

like image 375
DavidDev Avatar asked Mar 25 '26 02:03

DavidDev


1 Answers

If you cannot/don't want to use ES6 one approach is to use composition. Just wrap the LibraryComponent with your own Component and use a ref to access/override a special method.

var Wrapper = React.createClass({
  libLoaded: function(libComponent) {
    if (libComponent) {
      libComponent.onDrag = this.onDrag;
    }
  },
  onDrag: function() {
    return "Hello drag";
  },
  render: function() {
    return <LibraryComponent ref={this.libLoaded}/>;
  }
});
ReactDOM.render(
  <Wrapper/>,
  document.getElementById('container')
);

https://jsfiddle.net/2n0x666d/3/

like image 77
Richard Rutsche Avatar answered Mar 26 '26 14:03

Richard Rutsche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!