In react native how to reuse functions?

Saravana Kumar picture Saravana Kumar · Mar 9, 2017 · Viewed 8.7k times · Source

I need access functions from another page in react native .

Example :

validateEmail = (email) => {
// ---- Code ----
}

I need access that function in both login.js and registration.js

Answer

MattYao picture MattYao · Mar 9, 2017

I can give you a quick example which I use in my current project.

You can follow the steps:

1.Create a /utils folder which you can put all the shared functions files for example datetimeHelper.js

const dateTimeHelper = {
  getFormattedDatetime: (datetime) => {
    return moment.utc(datetime).local().format('MMM Do, YYYY, h:mm a');
  }
}

export default datetimeHelper;

2.Import the file into where you need it:

import datetimeHelper from './utils/datetimeHelper.js';

3 You can call the functions:

datetimeHelper.getFormattedDatetime(MY_DATETIME);