Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monkey Patching React Components

Tags:

Let's say I define a component like this:

const myComponent = class MyComponent extends React.Component {}

and later I would like to add a constructor to the defined component like this:

myComponent.constructor = function(props) {
  super(props)
  this.state = { hello: 'world' }
}

Does anyone know if this is possible? If so, does anyone know what differences in implementation are required compared to the above? Thanks!

like image 752
SMLMRKHLMS Avatar asked Aug 21 '16 17:08

SMLMRKHLMS


People also ask

What is monkey patching react?

What is Monkey patching? A monkey patch is a way for a program to extend or modify supporting system software locally. Monkey patching replace methods / classes / attributes / functions at runtime.

What is the use of monkey patching?

Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. A monkey patch (also spelled monkey-patch, MonkeyPatch) is a way to extend or modify the runtime code of dynamic languages (e.g. Smalltalk, JavaScript, Objective-C, Ruby, Perl, Python, Groovy, etc.)

What does monkey Patch_all () do?

A monkey patch is a way to change, extend, or modify a library, plugin, or supporting system software locally. This means applying a monkey patch to a 3rd party library will not change the library itself but only the local copy of the library you have on your machine.

Why is it called monkey patching?

Etymology. Apparently from earlier guerilla patch (“code that sneakily changes other code”), understood as gorilla patch. A monkey patch was then a more carefully written instance of such a patch. Or simply derived from monkey (“to mess with”, verb).


1 Answers

You can not override constructor for es6 classes. You can do it with es5 classes, so it would work (and be brittle) with babel.

For other methods you would do

MyComponent.prototype.methodName = function() {}

This is IMO a missing feature as it would allow better dependency injection.

If TC39 should stumble onto this page I would love to have Reflect.setConstructor.

like image 132
user3654410 Avatar answered Sep 22 '22 16:09

user3654410