Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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')); 
like image 926
nancy Avatar asked Jan 31 '17 04:01

nancy


People also ask

Can you have multiple Classnames in React?

We can add a multiple class names to the react element conditionally; by using template literals, ternary operator.


2 Answers

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>         );     } } 
like image 76
patrick Avatar answered Sep 19 '22 13:09

patrick


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')); 
like image 23
Saurabh Bayani Avatar answered Sep 20 '22 13:09

Saurabh Bayani