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>
        );
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

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.
this is a class ?
@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?
Yes agreed it could/should be camelCase. I don’t think having a class is necessary I prefer functional composition over inheritance where possible
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.
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 Comments

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.
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.
What is the significance of using the static method here?
If you're only using static methods, is there any reason to make the helper a class vs just a normal class?
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

Comments

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.