Custom Functions allow you to add functions and hooks to your apps. Functions can be created in the Custom Code modal.

Function Types

There are two types of Custom Functions - Global and Screen.

Global Functions

Global functions let you create functions that are available to all Screens in your app. You can set parameters, import Files, read and set App Variables and Device Variables, and enable some additional Expo and React Native packages.

Screen Functions

Screen functions let you create functions and hooks that can be used in the Screen on which they were created. You can set parameters, import Files, read and set App Variables and Device Variables, and enable some additional Expo and React Native packages.

In addition to having access to App and Device variables, Screen functions also have direct access to set and get any Screen Variables you have created on the same Screen. Read more about that in Variables in Custom Code.

Screen functions can also be configured to run as hooks, such as mountEffect, useEffect, or you can implement custom inline hooks.

Configuration

PropertyDescription
TypeCustom Function - This is just a plain function

Custom Hook - This is a React Native Hook
NameFor Custom Functions, the name that will be referenced in code to call the function.

For Custom Hooks, choose between:

- mountEffect - An effect hook invoked immediately after the component has mounted (similar to a React class’s componentDidMount lifecycle function)
- useEffect - Invoked immediately after the component has been updated (similar to a React class’s componentDidUpdate lifecycle function)
- customInlineHook - JavaScript function whose name starts with ”use” and that may call other Hooks
DescriptionAn optional explanation of the function's purpose / what the function does.
CategoryAn optional category to group functions together in the functions list
ParametersParameters are variables assigned to values you pass into your function when they are used. The variables are available in your function's code.
Return TypeThe return type helps Draftbit know what data type to expect when your function returns a value
Custom File ImportsIf you have Custom Files and want to make them available to your Custom Functions, you can select them here
Is Asynchronous FunctionEnable this if you need to await a response inside your function
Read App VariablesEnable this if your function needs to read App or Device Variables. They will be available to you via the Variables variable and used like Variables.username
Set App VariablesEnable this if your function needs to set App or Device Variables. They will be available to you via the setGlobalVariableValue variable and used like setGlobalVariableValue({ key: 'myVar', value: 'new value' })

Running Functions

From Triggers

After you've saved a function, you can run the function using a Run Custom Function Action from any available component Triggers. For example, you can run your function when a Button is pressed using its On Press Trigger.

From Other Functions

You can also execute Global Functions from other functions by leveraging Custom Files.

Global Functions are stored in the /global-functions directory and Custom Files are by default stored in /custom-files directory. Inside your Custom Files, you can import any Global Functions that you've created.

Example

For example, if you have two Global Functions named 'add' and 'subtract' and you want to call those functions from another Global Function named 'doMath'. You can create a Custom File that exports those functions and then import that Custom File into other functions.

Global Function named 'add'

function add(value, addition) {
  return value + addition;
}

Global Function named 'subtract'

function subtract(value, subtraction) {
  return value - subtraction;
}

Custom File named 'CustomFunctions'

import add from '../global-functions/add'
import subtract from '../global-functions/subtract'

export { add, subtract }

Finally, in the 'doMath' function where you want to call the other functions, you'd import the created CustomFunctions file and use the 'add' and 'subtract' functions.

Global or Screen Function named 'doMath'

import * as CustomFunctions from '../custom-files/CustomFunctions'

function doMath(value) {
  let addResult = CustomFunctions.add(value, 10);
  let subtractResult = CustomFunctions.subtract(value, 5)
  return addresult * subtractResult;
}

As Transform

You can also use your functions to transform values, such as Variables, when passing them in your app. Read more in the Transform Functions doc.

Using Variables in Functions

You can use App Variables, Device Variables, and Screen Variables inside your Custom Functions.

See the docs on Variables with Custom Code

Using Files in Functions

You can import your Custom Files to make them available to your functions by selecting them from the dropdown under the Custom File Imports section.

This is helpful for making common custom code available throughout your app or exposing modules from packages you've imported into your app project.

See more about importing and using packages

Copying Screen Functions

It's possible to copy Screen Functions from one Screen to another.

  • Open the Screen Function you want to copy
  • Scroll to the bottom of the left panel in the Edit Screen Function modal
  • Under the Copy To section, select a Screen to which you want to copy the current function

Adding Available Expo SDK Packages

This section provides usable examples for some of the Expo packages we've made available by default for use in Custom Functions.

expo-clipboard

To use expo-clipboard in the app, create a new custom function by following the steps:

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the function.
  • Enter the Description of the function (optional).
  • Select the Expo Clipboard package from the Available Packages list.
  • Enter the code for the function in the editor and then click Save.
  • Select the component (such as a Button or Touchable) on the screen from Components tree.
  • To trigger this function, go to Interactions Tab in the Properties Panel, click the '+' button next to Action, and select the Custom Function.
  • Then, provide a value to the Custom Function by selecting the Name of the function from the drop-down menu.

Code snippet used in the above example:

Clipboard.setString('Some Input');

RN Alert

To use Alert dialog-box in the app, create a new custom function by following the steps:

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the function.
  • Enter the Description of the function (optional).
  • Select the RN Alert package from the Available Packages list.
  • Enter the code for the function in the editor and then click Save.
  • Select the component (such as a Button or Touchable) on the screen from the Components tree.
  • To trigger this function, go to Interactions Tab in the Properties Panel, click the '+' button next to Action, and select the Custom Function.
  • Then, provide a value to the Custom Function by selecting the Name of the function from the drop-down menu.

Code snippet used in the above example:

Alert.alert(
  "Alert",
  "Press OK or Cancel.",
  [
    {
      text: "Cancel",
      onPress: () => console.log("Cancel Pressed"),
      style: "cancel",
    },
    {
      text: "OK",
      onPress: () => console.log("OK Pressed"),
    },
  ],
  { cancelable: false }
);

expo-constants

Expo Constants is a package that provides the system's information. In a mobile app, the system is the device on which the app is running. To use it, let's create a new custom function that enables a prompt when tapped by following the steps and show the device's name. The device's name here is just one of the properties available on Constants.

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the function.
  • Enter the Description of the function (optional).
  • Select the Expo Constants and RN Alert from the Available Packages list.
  • Enter the code for the function in the editor and then click Save.
  • Select the component (such as a Button or Touchable) on the screen from the Components tree.
  • To trigger this function, go to Interactions Tab in the Properties Panel, click the '+' button next to Action, and select the Custom Function.
  • Then, provide a value to the Custom Function by selecting the Name of the function from the drop-down menu.

Code snippet used in the above example:

const deviceName = Constants.deviceName;

Alert.alert(
  "Your Device Name is:",
  deviceName.toString(),
  [    
    {
      text: "OK",
      onPress: () => console.log("OK Pressed"),
    },
  ],
  { cancelable: false }
);

RN Vibrate

React Native has a Vibration module to handle the functionality on a device. In the following example, let's create two custom functions. The first function will start a vibration pattern at an interval of one second in between, in form of a loop. The second function will allow the pattern to stop.

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the first function.
  • Enter the Description of the function (optional).
  • Select the RN Vibrate package from the Available Packages list.
  • Enter the code for the function in the editor and then click Save.
  • Repeat the steps to create a second custom function.
  • Select the component (such as a Button or Touchable) on the screen from the Components tree.
  • To trigger the first custom function, go to Interactions Tab in the Properties Panel, click the '+' button next to Action, and select the Custom Function.
  • Then, provide a value to the Custom Function by selecting the Name of the function from the drop-down menu.
  • Repeat the steps to add the second Custom Function on another touchable component.

Code snippet used in the above example:

// create first function to start vibration
const PATTERN = [1000, 1000, 1000];

Vibration.vibrate(PATTERN, true);

// create second function: to stop vibration
Vibration.cancel();

📘

Android apps require the android.permission.VIBRATE permission to be enabled explicitly. You can enable this permission by:

  • Go to Settings tab in the left menubar. It opens up the Project Settings modal.
  • In the Advanced Settings menu, go to ANDROID > Permissions and check the box Vibrate.

expo-permissions

To use expo-permissions, you will have to create a custom function by following the steps:

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the function.
  • Enter the Description of the function (optional).
  • Asking for permission is an asynchronous process. Enable the asynchronous function option.
  • Select the Expo Permissions from the Available Packages list.
  • Enter the code for the function in the editor and then click Save.
  • Click the 'Add' button in the modal to create an useEffect hook. It will be responsible for triggering the Custom function.
  • Enter the name of the custom function in the editor for useEffect hook and then click Save.

Code snippet used in the above example:

// first create a custom function & name it "enablePermission"
await Permissions.askAsync(Permissions.LOCATION);

// second, create a useEffect hook
enablePermission();

RN Platform

Platform is a package from React Native that provides a module to detect the platform (iOS or Android) in which the app is running.

To use Platform, you will have to create a custom function by following the steps:

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the function.
  • Enter the Description of the function (optional).
  • Select the RN Platform and RN Alert from the Available Packages list.
  • Enter the code for the function in the editor and then click Save.
  • Select the component (such as a Button or Touchable) on the screen from the Components tree.
  • To trigger this function, go to Interactions Tab in the Properties Panel, click the '+' button next to Action, and select the Custom Function.
  • Then, provide a value to the Custom Function by selecting the Name of the function from the drop-down menu.

Code snippet used in the above example:

const OSName = Platform.OS === 'ios' ? 'iOS' : 'android';

Alert.alert(
  "The OS Name is:",
  OSName.toString(),
  [    
    {
      text: "OK",
      onPress: () => console.log("OK Pressed"),
    },
  ],
  { cancelable: false }
);

RN Keyboard

Keyboard is a package from React Native that provides methods to control keyboard events.

To use Keyboard, you will have to create a custom function by following the steps:

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the function.
  • Enter the Description of the function (optional).
  • Enter the code for the function in the editor and then click Save.
  • Click the 'Add' button in the modal to create an useEffect hook. It will be responsible for triggering the Custom Function.
  • Select the RN Keyboard from the Available Packages list.
  • Enter the name of custom function in the editor for useEffect hook and then click Save.

The above example triggers an alert dialog box when the TextInput field is touched or clicked. Code snippet used in the above example:

// first create a custom function
alert("Keyboard Shown");

// second, create a useEffect hook
Keyboard.addListener("keyboardDidShow", keyboardDidShow);

// cleanup function
return () => {
      Keyboard.removeListener("keyboardDidShow", keyboardDidShow);
      
};

expo-sharing

The expo-sharing is a package that allows sharing files directly with other compatible applications.

Let's create an example where using Expo Image Picker and Expo Sharing. In the example below, create two custom functions to:

  • ask permission to access a device's media library.
  • create a useEffect hook function to trigger the alert dialog box for asking permission.
  • create a custom function to select the image from the media library and then enable sharing it using expo-sharing.

Create a custom function and hooks to ask for media library permission using expo-image-picker.

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the function.
  • Enter the Description of the function (optional).
  • Enable the asynchronous function option.
  • Select the Expo Image Picker and RN Alert from the Available Packages list.
  • Enter the code for the function in the editor and then click Save.
  • Click the 'Add' button in the modal to create an useEffect hook. It will be responsible for triggering the Custom Function.
  • Enter the name of the custom function in the editor for useEffect hook and then click Save.

Create another custom function to select an image from the media library and open an action sheet to share the file.

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the function.
  • Enter the Description of the function (optional).
  • Enable the asynchronous function option.
  • Select the Expo Image Picker and Expo Sharing from the Available Packages list.
  • Enter the code for the function in the editor and then click Save.
  • Select the component (such as a Button or Touchable) on the screen from the Components tree.
  • To trigger this function, go to Interactions Tab in the Properties Panel, click the '+' button next to Action, and select the Custom Function.
  • Then, provide a value to the Custom Function by selecting the Name of the function from the drop-down menu.

Code snippet used in the above example:

// first custom function & name it "pickerPermissions"
const {status} = await ImagePicker.requestMediaLibraryPermissionsAsync();

if (status !== 'granted') {
Alert.alert(
           "Permission Denied",
  `You denied the permissions.`,
  [    
    {
      text: "OK",
      onPress: () => console.log("OK Pressed"),
    },
  ],
  { cancelable: false }
);
}

// create a useEffect hook to trigger first custom function
pickerPermissions();

// second custom function
let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
});

if(!result.cancelled) {
  Sharing.shareAsync(result.uri);
}

RN Appearance

Appearance is a package that exposes information about the user's appearance preferences, such as their preferred color scheme (light or dark).

To use Appearance, you will have to create a custom function by following the steps:

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the function.
  • Enter the Description of the function (optional).
  • Select the RN Appearance from the Available Packages list.
  • Enter the code for the function in the editor and then click Save.
  • Select the component (such as a Button or Touchable) on the screen from the Components tree.
  • To trigger this function, go to Interactions Tab in the Properties Panel, click the '+' button next to Action, and select the Custom Function.
  • Then, provide a value to the Custom Function by selecting the Name of the function from the drop-down menu.

Code snippet used in the above example:

alert(`Current ColorScheme ${Appearance.getColorScheme().toString()}`)

Async Storage

AsyncStorage is a package that provides an asynchronous, unencrypted, persistent, key-value storage solution. To use it, you will have to create the following custom function:

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the function.
  • Enter the Description of the function (optional).
  • Select the AsyncStorage from the Available Packages list.
  • Enter the code for the function in the editor and then click Save.
  • Select the component (such as a Button or Touchable) on the screen from the Components tree.
  • To trigger this function, go to Interactions Tab in the Properties Panel, click the '+' button next to Action, and select the Custom Function.
  • Then, provide a value to the Custom Function by selecting the Name of the function from the drop-down menu.

Code snippet used in the above example:

try {
  const data = 'Some Value'
  const value = JSON.stringify(data);
  await AsyncStorage.setItem('@MyDraftbitApp', value)
} catch (e){
  alert(`${e}`)
}

expo-sensors

The expo-sensors provides various APIs for accessing device sensors to measure motion, orientation, pressure, magnetic fields, and step count. The APIs is available using the following sensors:

  • Accelerometer
  • Barometer
  • Gyroscope
  • Magnetometer
  • Pedometer

To use Pedometer, create a custom function by following the steps:

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the function.
  • Enter the Description of the function (optional).
  • Select the Expo Sensors package from the Available Packages list.
  • Enter the code for the function in the editor and then click Save.
  • Select the component (such as a Button or Touchable) on the screen from the Components tree.
  • To trigger this function, go to Interactions Tab in the Properties Panel, click the '+' button next to Action, and select the Custom Function.
  • Then, provide a value to the Custom Function by selecting the Name of the function from the drop-down menu.

Code snippet used in the above example:

Sensors.Pedometer.watchStepCount(result => {
  alert(result.steps);
});

expo-sms

expo-sms is a package that provides access to the system's UI/app for sending SMS messages.

To use expo-sms, create a custom function by following the steps:

  • Click the 'Add' button in the Custom Code modal.
  • In the Add Function modal, enter the Name of the function.
  • Enter the Description of the function (optional).
  • Toggle on the 'Is function asynchronous' option.
  • Select the Expo SMS package from the Available Packages list.
  • Enter the code for the function in the editor and then click Save.
  • Select the component (such as a Button or Touchable) on the screen from the Components tree.
  • To trigger this function, go to Interactions Tab in the Properties Panel, click the '+' button next to Action, and select the Custom Function.
  • Then, provide a value to the Custom Function by selecting the Name of the function from the drop-down menu.

Code snippet used in the above example:

const isAvailable = await SMS.isAvailableAsync();
if (isAvailable) {
  await SMS.sendSMSAsync(inputPhone, inputMsg);
} else {
  alert('Message service not available on this device');
}

What’s Next

Learn about adding custom Files to your app project