25

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'));

4 Answers 4

27

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>
        );
    }
}
5
  • 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.
    – patrick
    Jan 31, 2017 at 7:41
  • 1
    this is a class ? Jul 11, 2017 at 23:15
  • @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? Oct 22, 2018 at 7:03
  • Yes agreed it could/should be camelCase. I don’t think having a class is necessary I prefer functional composition over inheritance where possible
    – patrick
    Oct 22, 2018 at 7:05
  • 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.
    – Aylii
    Nov 28, 2018 at 0:14
20

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'));
4
  • 1
    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.
    – Bogie
    Mar 14, 2019 at 6:24
  • 1
    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.
    – ralcazar
    Jun 23, 2020 at 2:00
  • 1
    What is the significance of using the static method here?
    – Yogesh
    Feb 16, 2021 at 19:04
  • If you're only using static methods, is there any reason to make the helper a class vs just a normal class? Mar 26, 2022 at 18:36
8

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

3

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.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.