179

Though there is a similar question I am failing to create a file with multiple functions. Not sure if the method is already outdated or not as RN is evolving very fast. How to create global helper function in react native?

I am new to React Native.

What I want to do is to create a js file full of many reusable functions and then import it in components and call it from there.

What I have been doing so far might look stupid but I know you will ask for it so here they are.

I tried creating a class name Chandu and export it like this

'use strict';
import React, { Component } from 'react';
import {
  AppRegistry,
  Text,
  TextInput,
  View
} from 'react-native';


export default class Chandu extends Component {

  constructor(props){
    super(props);
    this.papoy = {
      a : 'aaa'
    },
    this.helloBandu = function(){
      console.log('Hello Bandu');
    },
  }

  helloChandu(){
    console.log('Hello Chandu');
  }
}

And then I import it in any required Component.

import Chandu from './chandu';

And then call it like this

console.log(Chandu);
console.log(Chandu.helloChandu);
console.log(Chandu.helloBandu);
console.log(Chandu.papoy);

The only thing that worked was the first console.log, which means that I'm importing the correct path, but not any others.

What is the correct way to do this please?

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
cjmling
  • 6,896
  • 10
  • 43
  • 79

7 Answers7

261

Quick note: You are importing a class, you can't call properties on a class unless they are static properties. Read more about classes here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

There's an easy way to do this, though. If you are making helper functions, you should instead make a file that exports functions like this:

export function HelloChandu() {

}

export function HelloTester() {

}

Then import them like so:

import { HelloChandu } from './helpers'

or...

import functions from './helpers' then functions.HelloChandu

TallOrderDev
  • 469
  • 4
  • 15
zackify
  • 5,314
  • 2
  • 22
  • 28
  • Ok I got it Thanks. Got to read some from here http://exploringjs.com/es6/ch_modules.html – cjmling Jul 15 '16 at 17:53
  • 4
    What about exporting an object instead, that contains a bunch of functions? Also what would be be the pros and cons of exporting such an object vs exporting a class with static properties? – hippietrail Sep 04 '17 at 02:00
  • 2
    Using named exports like we are here is just an object being exported. This is why you can destructure on the import. Do `import functions from './helpers'`. `functions. HelloChandu` will be there. functions is an object containing all the functions. Read up on export here :) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export – zackify Sep 05 '17 at 14:16
  • 2
    The con of using a bunch of static properties on a class is that you have a class for no reason. It's like using an api that you don't need. Why would you `new` up a class just for static properties? Export a function in that case – zackify Sep 05 '17 at 14:17
  • 1
    Stylistically speaking, aren't functions in js usually "lower camel case"? – Woodchuck Oct 02 '19 at 22:36
  • 1
    @JWoodchuck yes you are correct. but it depends. A react component would be a function that has the first letter capital, due to how React + jsx works. But in other cases it seems lower camel is the norm – zackify Oct 11 '19 at 02:32
  • `import functions from './helpers'` didn't work for me. I had to do `import * as functions from './helpers'` – Joshua Augustinus Jul 07 '20 at 22:38
110

An alternative is to create a helper file where you have a const object with functions as properties of the object. This way you only export and import one object.

helpers.js

const helpers = {
    helper1: function(){

    },
    helper2: function(param1){

    },
    helper3: function(param1, param2){

    }
}

export default helpers;

Then, import like this:

import helpers from './helpers';

and use like this:

helpers.helper1();
helpers.helper2('value1');
helpers.helper3('value1', 'value2');
c-chavez
  • 7,237
  • 5
  • 35
  • 49
  • I know it's been a while but a followup question: Is there a neat way to call one of the helper functions from within another helper function? I.e helper2: function(param1){ helper1(); } ? I tried with this.helper1() and just helper1() but neither worked. – Johan May 23 '19 at 20:31
  • 1
    @Johan try `helper2: function(param1){ helpers.helper1(); }` – c-chavez Jun 12 '19 at 06:29
  • This is the method you'd use if you want to directly access methods from a singular module/object. Thank you! – HaulinOats Sep 07 '19 at 16:04
  • 1
    I love this one. Declare as object and expose the method after dot. Better when use intellisense to auto import for faster development. – Luiey Nov 15 '21 at 09:43
31

I am sure this can help. Create fileA anywhere in the directory and export all the functions.

export const func1=()=>{
    // do stuff
}
export const func2=()=>{
    // do stuff 
}
export const func3=()=>{
    // do stuff 
}
export const func4=()=>{
    // do stuff 
}
export const func5=()=>{
    // do stuff 
}

Here, in your React component class, you can simply write one import statement.

import React from 'react';
import {func1,func2,func3} from 'path_to_fileA';

class HtmlComponents extends React.Component {
    constructor(props){
        super(props);
        this.rippleClickFunction=this.rippleClickFunction.bind(this);
    }
    rippleClickFunction(){
        //do stuff. 
        // foo==bar
        func1(data);
        func2(data)
    }
   render() {
      return (
         <article>
             <h1>React Components</h1>
             <RippleButton onClick={this.rippleClickFunction}/>
         </article>
      );
   }
}

export default HtmlComponents;
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
hannad rehman
  • 4,133
  • 3
  • 33
  • 55
  • If I want to call redux action in func1 with this.props.action... how do I change the code in React component class? I'm getting undefined is not an object (evaluating '_this.props.actions') – Justin Lok Aug 08 '17 at 05:37
  • i got what you are trying to achieve here. what I can suggest is pass a callback function to func1. and inside the callback function, you can dispatch your action with this.props.action. one more thing you need to keep in mind is that you will have to mapDispatchToProps, I hope you are doing it. – hannad rehman Aug 08 '17 at 08:59
  • why const? is it makes any difference an export keyword before the function name? – Milon Sep 09 '17 at 03:12
  • @DinIslamMilon its only my preference. if i have functions in seperate file/ module. i will make them as const or properties of objects. i dont use direct functions or export direct functions. i dont see any harm using otherwise – hannad rehman Sep 14 '17 at 09:20
29

To achieve what you want and have a better organisation through your files, you can create a index.js to export your helper files.

Let's say you have a folder called /helpers. Inside this folder you can create your functions divided by content, actions, or anything you like.

Example:

/* Utils.js */
/* This file contains functions you can use anywhere in your application */

function formatName(label) {
   // your logic
}

function formatDate(date) {
   // your logic
}

// Now you have to export each function you want
export {
   formatName,
   formatDate,
};

Let's create another file which has functions to help you with tables:

/* Table.js */
/* Table file contains functions to help you when working with tables */

function getColumnsFromData(data) {
   // your logic
}

function formatCell(data) {
   // your logic
}

// Export each function
export {
   getColumnsFromData,
   formatCell,
};

Now the trick is to have a index.js inside the helpers folder:

/* Index.js */
/* Inside this file you will import your other helper files */

// Import each file using the * notation
// This will import automatically every function exported by these files
import * as Utils from './Utils.js';
import * as Table from './Table.js';

// Export again
export {
   Utils,
   Table,
};

Now you can import then separately to use each function:

import { Table, Utils } from 'helpers';

const columns = Table.getColumnsFromData(data);
Table.formatCell(cell);

const myName = Utils.formatName(someNameVariable);

Hope it can help to organise your files in a better way.

Italo Borges
  • 2,355
  • 5
  • 34
  • 45
3

If you want to use class, you can do this.

Helper.js

  function x(){}

  function y(){}

  export default class Helper{

    static x(){ x(); }

    static y(){ y(); }

  }

App.js

import Helper from 'helper.js';

/****/

Helper.x
G.Guvenal
  • 149
  • 7
2

i prefer to create folder his name is Utils and inside create page index that contain what that think you helper by

const findByAttr = (component,attr) => {
    const wrapper=component.find(`[data-test='${attr}']`);
    return wrapper;
}

const FUNCTION_NAME = (component,attr) => {
    const wrapper=component.find(`[data-test='${attr}']`);
    return wrapper;
}

export {findByAttr, FUNCTION_NAME}

When you need to use this it should be imported as use "{}" because you did not use the default keyword look

 import {FUNCTION_NAME,findByAttr} from'.whare file is store/utils/index'
cjmling
  • 6,896
  • 10
  • 43
  • 79
Mohammed Al-Reai
  • 2,344
  • 14
  • 18
2

Create a file with name e.g Utils.js and use export with all functions.

export function firstFunction(){
}

export function secondFunction(){
}

Now there are two ways you can import and use these functions

  1. import them separately as
import {firstFunction, secondFunction} from './Utils'

and use them as

firstFunction()
secondFunction()
  1. import them by giving generic name as
import * as Utils from './Utils'

and use them as

Utils.firstFunction()
Utils.secondFunction()
Sohaib Khan
  • 517
  • 5
  • 9