how to create common helper class in React JS using ES6 which is used by another component?

37,354

Solution 1

Create a file called helpers.js

//helpers.js

export const AjaxHelper = (url) => {
    return (
      //ajax stuff here
    );
}

Then in your component:

import React from 'react';
import {render} from 'react-dom';
import {AjaxHelper} from "./path/to/helpers.js"

class App extends React.Component {

    constructor(props) {
        super(props);
        let myajaxresult = AjaxHelper(url);
    }

    render () {
        return(
        <p> Hello React!</p>
        );
    }
}

Solution 2

There is one more approach by wrapping it by a class rather than keeping all methods open and floating around utils.js

//utilsjs
default export class Utils {
    static utilMethod = (data) => {
        return (
          //methods stuff here
        );
    }
}

and then in your component

import React from 'react';
import {render} from 'react-dom';
import Utils from "./utils"

 class App extends React.Component {

    constructor(props) {
        super(props);
        let myData = {}; // any arguments of your
        Utils.utilMethod(myData);

    }

    render () {
        return(
        <p> Hello React!</p>
        );
    }
}

render(<App/>, document.getElementById('app'));

Solution 3

The way that you've exported the class requires a new instance for each module you import it into. You can, instead, use a single instance as you've mentioned by exporting an instantiated AjaxHelperClass object rather than the class definition -- something like

export default new AjaxHelperClass();

This effectively gives you a global object. When importing the object, you can call its member functions i.e AjaxHelperClass.ResturantAPI();. Another option is to use static methods instead if all you want to use the class for is a namespace -- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

Solution 4

Another way you can do it that doesn't involve you having to import specific helper methods is just by exporting an Object in your helper file:

Helpers.js

export default { 

  connectToRestaurant: (url) => {

      $.ajax({
          url : url,
          success : function(res){}
      });

  },

  orderPizza: ( toppings = {} ) => {
    // Order a pizza with some sweet toppings.
  }

}

index.js

import Helpers from "Helpers";

Helpers.connectToRestaurant( "http://delicious.com/" );

Helpers.orderPizza( { cheese: true, pepperoni: true } );

I think there might be a package size penalty by not specifically including the functions from the modules, but the convenience factor, in my opinion, can often outweigh that penalty.

Share:
37,354

Related videos on Youtube

nancy
Author by

nancy

Updated on June 01, 2020

Comments

  • nancy
    nancy almost 4 years

    I am a new in react js, my problem is I want to create a class which will work as global helper which I want to utilzed in another class or component.

    Use case for e.g First I want to fetch all resturant list keyword entered by user if user select any resturant then I want to get resturant details. in this use case I have to make two ajax call I want to create global ajax helper function which I can use in other components.

    class AjaxHelperClass{
    
        ResturantAPI(url){
    
            $.ajax({
                url : url,
                success : function(res){}
            });
    
        }
    }
    
        export default AjaxHelperClass;
    

    in my another component that use from my AjaxHelperClass function :

    import React from 'react';
    import {render} from 'react-dom';
    import {AjaxHelperClass} from "./module/AjaxHelperClass"
    
    class App extends React.Component {
    
        constructor(props) {
            super(props);
    
          ///  AjaxHelperClass.ResturantAPI(); // or
        let myajaxresult= new AjaxHelperClass(url);
    
        }
    
        render () {
            return(
            <p> Hello React!</p>
            );
        }
    }
    
    render(<App/>, document.getElementById('app'));
    
  • patrick
    patrick over 7 years
    Nice one @nancy. You can also add additional helpers to the helpers.js and instead of exporting a default you add export in front of the const SomeFunction.
  • RenaissanceProgrammer
    RenaissanceProgrammer almost 7 years
    this is a class ?
  • Saurabh Bayani
    Saurabh Bayani over 5 years
    @patrick, if AjaxHelper is a helper "method" then I think it should not start with the capital letter(as per convention). Also, what is your opinion on making HelperClass and then having "ajaxHelper" as a static method?
  • patrick
    patrick over 5 years
    Yes agreed it could/should be camelCase. I don’t think having a class is necessary I prefer functional composition over inheritance where possible
  • Aylii
    Aylii over 5 years
    Seems like this may not be working anymore (at least for me), what worked was defining the function as such > export const AjaxHelper = () => {} instead of export default AjaxHelper at the bottom.
  • Bogie
    Bogie about 5 years
    This is a very useful way to approach it, especially when you will have multiple functions (or ajax calls in the OP's case). Allows for concise calling of several helper functions throughout your app.
  • ralcazar
    ralcazar almost 4 years
    This is what I'm looking for. Why I didn't think of the static methods :). I will be working with HTML canvas inside ReactJS where I will be expecting a lot methods building up inside a single component and I don't want my component packed with too many methods.
  • Yogesh
    Yogesh about 3 years
    What is the significance of using the static method here?
  • Travis Howell
    Travis Howell about 2 years
    If you're only using static methods, is there any reason to make the helper a class vs just a normal class?