Problem
All JSX elements are first created as objects (WitVault explains how JSX is transpiled to plain JS that can run in the browser). React takes those objects and their properties that React supports and maps them to DOM elements. If there are properties that React does not know about, it will show a warning because it's likely a case of either "you don't know what you are doing" or "you made a typo", and therefore you won't get the behavior that you expect.
Since you edited the prototype of Object, all objects, also those created by React, get the property sum
, and for primitive html elements React does not know how to map a sum
property.
As Juan Mendes pointed out, extending native objects is bad practice. If you extend Object.prototype
in a React project you really cant avoid the problem you are experiencing.
Solution 1: Export/Import util function
Since React comes with browserify you can instead import utility methods. This has two advantages:
- You don't need to extend native objects
- You clearly express where the methods used come from, be cause they have an import statement in the file where it's used.
In ES6
// util/objectSum.js
export default function objectSum(object) { ... };
// anotherFile.js
import objectSum from 'utils/objectSum.js'; // assuming utils/ is directly under the root path of your project (root path can be configured in webpack.config if you use webpack)
const object = ?; // the object you want to sum
const sum = objectSum(object);
In ES5
// util/objectSum.js
module.exports = function(object) { ... };
// anotherFile.js
var objectSum = require('utils/objectSum.js'); // assuming utils/ is directly under the root path of your project (root path can be configured in webpack.config if you use webpack)
const object = ?; // the object you want to sum
const sum = objectSum(object);
Solution 2: Using ES6 classes
In ES6 you can also create a class with the sum method. Here's an example:
class NumberList {
constructor(arrayOfNumbers) {
this.numbers = arrayOfNumbers;
this.sum = this.sum.bind(this);
}
sum() {
return this.numbers.reduce((sum, next) => sum + next, 0);
}
}
const numberList = new NumberList([1, 2, 3]);
numberList.sum(); // -> 6