0

How can I export this method to another React Component?

  // utils.js 

   Array.prototype.last_element = function() {
       const last_index = this.length-1;
       return this[last_index];
    };

    export default ... ? 
  // main.jsx

  import ... ? from './utils.js';
  
  const arr = [1 , 2 , 3];

  console.log(arr.last_element());
wangdev87
  • 8,611
  • 3
  • 8
  • 31
Matt
  • 33
  • 6
  • You don't need to import any specific name, as long as that module is loaded *anywhere* in your app `Array.prototype` gets patched. – jonrsharpe Nov 13 '20 at 17:46
  • And to clarify, the fact that you don't have to import this function, because it is global, is also why modifying globals us considered bad form. You _should_ have to import the functions you use, so you should not assign to `Array.prototype` like this. – loganfsmyth Nov 13 '20 at 18:26

1 Answers1

2

You don't need to export. Just import the file in the main.jsx.

// main.jsx
import "./utils.js";

However, since you are using React, you need to import utils.js only once in App.tsx or index.tsx because your main purpose is to define the Array prototype.

wangdev87
  • 8,611
  • 3
  • 8
  • 31
  • This link will help you understand in detail - https://stackoverflow.com/questions/50314657/js-export-an-array-prototype – wangdev87 Nov 13 '20 at 17:48
  • He is modifying a global object, why would he need to export/import it? – kind user Nov 13 '20 at 17:51
  • if utils.js where the array prototype is defined is not imported anywhere, then import that file is necessary – wangdev87 Nov 13 '20 at 17:53
  • The linked answer seems to address this problem sufficiently. It should probably just be marked a duplicate. – Brian Thompson Nov 13 '20 at 17:56
  • If only one variable/method is imported anywhere in the app from that file, the `Array` prototype will be modified. Even if in that file nothing is exported/imported anywhere and only the prototype mutation happens, perhaps a much better proposal would be to just move it to some `App.tsx` file or `index`. – kind user Nov 13 '20 at 18:00
  • agreed, i will update answer. – wangdev87 Nov 13 '20 at 18:02