181

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?

0

7 Answers 7

262

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

7
  • 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? Commented Sep 4, 2017 at 2: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 :) developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – zackify
    Commented Sep 5, 2017 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
    Commented Sep 5, 2017 at 14:17
  • 1
    Stylistically speaking, aren't functions in js usually "lower camel case"?
    – Woodchuck
    Commented Oct 2, 2019 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
    Commented Oct 11, 2019 at 2:32
115

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');
4
  • 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
    Commented May 23, 2019 at 20:31
  • 1
    @Johan try helper2: function(param1){ helpers.helper1(); }
    – c-chavez
    Commented Jun 12, 2019 at 6:29
  • This is the method you'd use if you want to directly access methods from a singular module/object. Thank you!
    – HaulinOats
    Commented Sep 7, 2019 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
    Commented Nov 15, 2021 at 9:43
32

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;
4
  • 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
    Commented Aug 8, 2017 at 5: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. Commented Aug 8, 2017 at 8:59
  • why const? is it makes any difference an export keyword before the function name?
    – Milon
    Commented Sep 9, 2017 at 3: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 Commented Sep 14, 2017 at 9: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.

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

Your Answer

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

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