How to create helper file full of functions in react native?

ReactjsReact Native

Reactjs Problem Overview


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. https://stackoverflow.com/questions/33539774/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?

Reactjs Solutions


Solution 1 - Reactjs

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

Solution 2 - Reactjs

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

Solution 3 - Reactjs

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;

Solution 4 - Reactjs

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.

Solution 5 - Reactjs

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

Solution 6 - Reactjs

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'

Solution 7 - Reactjs

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

2) import them by giving generic name as

import * as Utils from './Utils'

and use them as

Utils.firstFunction()
Utils.secondFunction()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncjmlingView Question on Stackoverflow
Solution 1 - ReactjszackifyView Answer on Stackoverflow
Solution 2 - Reactjsc-chavezView Answer on Stackoverflow
Solution 3 - Reactjshannad rehmanView Answer on Stackoverflow
Solution 4 - ReactjsItalo BorgesView Answer on Stackoverflow
Solution 5 - ReactjsG.GuvenalView Answer on Stackoverflow
Solution 6 - ReactjsMohammed Al-ReaiView Answer on Stackoverflow
Solution 7 - ReactjsSohaib KhanView Answer on Stackoverflow