Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export multiple class methods

I have several methods that return jsx objects that I want to be able to call from outside the class, currently, the only way I found that work is to export arrow functions from outside of the class in the same file, but I end up with too many functions out of the class.

So is there a way to export multiple class methods from the same file and keep them in the class?

I don't want to make a new class for each of those functions because they're related, and I need to call them out of the class so I'll be able to add them in Storybook.

Example of what I want:

//A.js 
class A{
  export foo() {return (<div>...</div>)}
  export bar() {...}
}

export default A

What I have now that works:

//A.js 
export default class A{
...
}
export const foo = () => {...}
export const bar= () => {...}
like image 698
shinzou Avatar asked May 06 '18 20:05

shinzou


1 Answers

If your methods does not rely on its own properties or variables (accessed using this), you might want to try using static methods

export default class A {
  static foo() {return (<div>...</div>)}
  static bar() {...}
  ...
}

And then, you can use it like so:

import A from './A';

A.foo();

The advantage of using static method is that you don't need to create an instance to use it. And, it does not get re-created when you create a new instance.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

Live Demo:

class A {  
  static foo() {
    return "foo() called";
  }
  
  static bar() {
    console.log(this.foo() + " from bar()");
  }
}

class B {
  constructor() {
    A.bar();
  }
}

new B();
like image 166
ionizer Avatar answered Sep 20 '22 05:09

ionizer