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

I am new in js reaction, my problem is that I want to create a class that will work as a global helper that I want to use in another class or component.

Use an example for an example. First I want to get all the resturant list keyword entered by the user if the user selects any restaurant, then I want to get information about the restaurants. in this case I have to make two ajax calls. I want to create a global ajax helper function that I can use in other components.

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

in my other component, which is used 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')); 
+6
source share
2 answers

Create a file called helpers.js

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

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> ); } } 
+8
source

The way you exported the class requires a new instance for each module it imports. Instead, you can use a single instance, as you mentioned, by exporting an instance of an AjaxHelperClass object rather than a class definition - something like

 export default new AjaxHelperClass(); 

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

+3
source

Source: https://habr.com/ru/post/1014575/


All Articles