paint-brush
Build a Mobile App Using React Native and the Salesforce Mobile SDK by@johnjvester
3,844 reads
3,844 reads

Build a Mobile App Using React Native and the Salesforce Mobile SDK

by John VesterMarch 22nd, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Check out how easy it is to start building a custom React Native application that leverages the Salesforce platform and the Salesforce Mobile SDK.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Build a Mobile App Using React Native and the Salesforce Mobile SDK
John Vester HackerNoon profile picture


Last July, I started writing a series focused on how the Salesforce platform can be utilized in a manner without a traditional Salesforce client. Here are links to the other articles in the series:



A graphical representation of the series could be summarized as shown below:


The illustration above demonstrates how various client frameworks can access the Salesforce data without actually utilizing clients provided by the Salesforce ecosystem.


Feature team developers may not be aware of the Salesforce Mobile SDK, which allows you to harness the power of the Salesforce Platform within standalone mobile apps. In this short series, I’ll demonstrate how to use the Salesforce Mobile SDK for custom mobile applications written in React Native, Android Studio, and Xcode.


A graphical representation of this new series could be summarized as shown below:


Benefits of the Salesforce Mobile SDK

The Salesforce Mobile SDK provides several benefits that software engineers can take advantage of:


  • Allows custom mobile device applications to utilize Salesforce features and functionality
  • Full access to Salesforce functionality (no need to reinvent the wheel)
  • Applications can be distributed using the native device’s application store
  • Push notifications from Salesforce can be processed
  • The ability to work with Salesforce data in an offline mode


If your application landscape utilizes Salesforce for key aspects of business operability, then you should consider leveraging the Salesforce Mobile SDK in order to introduce data maintained by Salesforce into key component locations to facilitate strong business decisions.

Benefits of Using React Native

If you are still reading this article, then there must be some interest in developing applications using the Salesforce ecosystem. If your current client base requires support for both Android and iOS devices, then the React Native framework should be at the top of your list to review.


A few key features for feature teams employing React Native are noted below:


  • Uses one code base for both Android and iOS devices
  • Leverages JavaScript (and TypeScript if desired) to avoid learning new languages
  • Provides a quick turnaround time to produce native clients running on mobile devices

Why Not Just Use HTML5?

Those with experience with Angular, React, Vue.js (and other client frameworks) may ask “why not just create a responsive HTML5 application?”


While the HTML5 approach is possible, limitations do exist when trying to access core components on mobile devices—like the camera. Additionally, session management and lack of access to secure storage may present deal-breakers in your Product Owner’s mind. Plus, mobile users tend to prefer native applications over browser-based applications on their devices.


For more information and a side-by-side analysis, take a look at the following breakdown provided by Salesforce:


About Native, HTML5, and Hybrid Development

Finny’s Foods: An Example Use Case

Having a son (Finny) born with special needs introduced a personal desire to gain an understanding and appreciation of the products we utilize in our daily life. Years before Finny was born, my wife (Nicole) and I lived a healthy lifestyle. However, as Nicole began deep diving into the list of ingredients included in the foods that were a part of our daily diet, we received a much-needed wakeup call.


Fast-forward to today, our diet contains very few processed foods, no gluten, low sugar, and very little dairy. As much as possible, our protein originates from grass-fed sources, and we always favor organic options. Don’t get me started on GMO.

For this series, our Finny’s Foods application provides a simple list of meals that are both acceptable to us and favored by Finny. For now, we will include two simple attributes for each meal:


  • Name of the meal
  • Rating (1 to 5, where a rating of 5 is an absolute favorite for Finny)


Over time, I plan to introduce other attributes (such as summary, ingredients, directions, and even a photo), but let’s walk before we run.

Getting Started with React Native

Aside from making sure I had git and npm installed on my MacBook Pro, I realized I needed a recent version of Node. I also needed to install TypeScript and the forcereact package, which I did using npm:


npm install -g typescript forcereact


Within the ./projects/jvc/salesforce-mobile-sdk folder on my local machine, I used the forcereact command to create the Finny’s Foods application in React Native:


forcereact create --platform=ios,android 
  --appname=FinnysFoods --packagename=com.gitlab.johnjvester.finnysfoods 
  --organization="johnjvester" --outputdir=FinnysFoods


The installer provided the following summary message:


********************************************************************************
*
*   Creating ios and android react_native application using Salesforce Mobile SDK
*     with app name:        FinnysFoods
*          package name:    com.gitlab.johnjvester.finnysfoods
*          organization:    johnjvester
*
*     in:                   FinnysFoods
*
*     from template repo:   https://github.com/forcedotcom/SalesforceMobileSDK-Templates#v9.1.1
*          template path:   ReactNativeTypeScriptTemplate
*
********************************************************************************


After installing the necessary dependencies, the React Native application base is ready. If I wanted to see the Hello World version of the application, I would simply do the following:


  1. Issue the npm start command
  2. Start Android Studio or Xcode
  3. Configure emulator (if one is not already configured)
  4. Run the app from Android Studio or Xcode


Before doing that, I wanted to start building the actual application. You can see a Hello World example in the “Leveraging Salesforce Using Mobile Applications Written (Once) In React Native” article from a prior series.


At this point, I decided to rename the /projects/jvc/salesforce-mobile-sdk/FinnysFoods folder to be /projects/jvc/salesforce-mobile-sdk/finnys-foods to match my current GitLab naming format.


For the remainder of this article, I will be working from the ./finnys-foods folder unless specified otherwise.

Adding Dependencies for the Star Rating System

To provide a better user experience, I wanted to include rating value next to the title in the application. Rather than just list the number value, I thought it would be nice to leverage the Font Awesome library to show a filled-in star to match the rating on the five-star scale. So, a rating of four stars would appear as shown below:


To accomplish this, I issued the following command to leverage the libraries from fortawesome:


npm i --save react-native-svg 
  @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons 
  @fortawesome/react-native-fontawesome @fortawesome/free-regular-svg-icons


At this point, the Font Awesome dependencies are available for use.

Creating the Meal Object in Salesforce

Before I could begin creating a new application in React Native, I needed to establish the Meal object in Salesforce.


I already had a Developer org that I could use. (You can create a new one here.) So, I simply logged in using my email address and password for that org. Next, I navigated to the Apps | App Manager and the Setup perspective in Salesforce.


I created a new Lightning App called Meal:



On the remaining screens in the setup, I went with all of the default settings and granted access to all Salesforce User Profiles.


Next, I visited the Objects & Fields | Object Manager menu option in the Salesforce Settings. Once I located the newly-created Meal item, I used the drop-down component to Edit the object.


I switched from the Details submenu to the Fields & Relationships option. I quickly realized I did not need to create a Name property for my Meal object, since Salesforce already took care of that for me. I just needed to add the Rating field.


Using the New button, I selected the number field type and populated Step Two as noted below:


I used the default values and saved my new field. Now, I can use both the name and rating fields in my React Native application, all because Salesforce automatically surfaced all of these schema changes to the RESTful API for this Salesforce org.


Using the Salesforce client, I went ahead and populated some source data to use for the development of the React Native application. Below is a summary of the submitted values:


Based upon the sample data, Finny always prefers ”Pizza” over “Chicken & Rice”.

Building the Meal Component in React Native

With the source object and data configured, I used my IntelliJ IDEA application to open the ./finnys-foods project for the first time.


Important Note: Keep in mind, we are going to point to the root folder (./finnys-foods) here, because this is where we will be doing the source development. Later, you will see how the Android Studio will use the android sub-folder when opening the same project. As you might expect, Xcode will use the ios sub-folder.


For simplicity, my React Native application is going to exist in the app.tsx file. Feature developers building business applications should consider adopting design principles for their React Native applications. The “React Native — Application architecture with Design pattern — corporate standards” article by Saurabh Shah provides some excellent information on this topic.

The app.tsx file was already populated with enough information to connect to Salesforce and make things quite easy to build upon.


I replaced the Record interface with a Meal interface as shown below:


interface Meal {
    Id: String,
    Name: String,
    Rating__c: number
}


As a result, I updated the Response and State interfaces accordingly:


interface Response {
    records: Meal[]
}

interface State {
    data : Meal[]
}


I renamed the React Component to MealListScreen as shown below:


class MealListScreen extends React.Component<Props, State> {


I updated the fetchData() method to call the Meal custom object created in Salesforce:


fetchData() {
        var that = this;
        net.query('SELECT Id, Name, Rating__c FROM Meal__c ORDER BY Name ASC LIMIT 100',
                  (response:Response) => {
                that.setState({data: response.records});
            },
                  (error) => console.log('Failed to query:' + error)
                 );
    }


I updated the render() method to show the name of the meal and the appropriate star rating:


render() {
        return (
            <View style={styles.container}>
              <FlatList
                data={this.state.data}
                renderItem={({item}) => {
                    return (
                        <Text style={styles.item}>{item.Name} {this.getStars(item.Rating__c)}</Text>
                    )
                } }
                keyExtractor={(item, index) => {
                    return item.Id.toString();
                }}
              />
            </View>
        );
    }


Finally, I updated the App to reflect the proper title of the application:


export const App = function() {
    return (
        <NavigationContainer>
          <Stack.Navigator>
            <Stack.Screen name="Finny's Foods" component={MealListScreen} ></Stack>
          </Stack.Navigator>
        </NavigationContainer>
    );
}


With these changes in place, we are ready to give the Finny’s Food app a try using Android Studio.

Finny’s Foods In Action

From the command line, I executed the npm start command in the ./finnys-foods folder. The following information was displayed:


> [email protected] start /Users/john.vester/projects/jvc/salesforce-mobile-sdk/finnys-foods
> node node_modules/react-native/local-cli/cli.js start

                                                          
               ######                ######               
             ###     ####        ####     ###             
            ##          ###    ###          ##            
            ##             ####             ##            
            ##             ####             ##            
            ##           ##    ##           ##            
            ##         ###      ###         ##            
             ##  ########################  ##             
          ######    ###            ###    ######          
      ###     ##    ##              ##    ##     ###      
   ###         ## ###      ####      ### ##         ###   
  ##           ####      ########      ####           ##  
 ##             ###     ##########     ###             ## 
  ##           ####      ########      ####           ##  
   ###         ## ###      ####      ### ##         ###   
      ###     ##    ##              ##    ##     ###      
          ######    ###            ###    ######          
             ##  ########################  ##             
            ##         ###      ###         ##            
            ##           ##    ##           ##            
            ##             ####             ##            
            ##             ####             ##            
            ##          ###    ###          ##            
             ###     ####        ####     ###             
               ######                ######               
                                                          
                 Welcome to React Native!
                Learn once, write anywhere



To reload the app press "r"
To open developer menu press "d"


Next, I opened Android Studio and imported the project from the ./finnys-foods/android folder, which was a Gradle project. Once ready, I used the Run menu option and selected the Run ‘app’ option, which also maps to the Shift-F10 shortcut. Keep in mind, I had already configured an Android device to emulate in the “Leveraging Salesforce Using Mobile Applications Written (Once) In React Native” article from a prior series.


The mobile device was displayed on my monitor, and I needed to press the CONTINUE option to grant the appropriate permissions.



First-time use will automatically redirect to a Salesforce login screen, where I used the same email address and password to access my Developer org. This is a really nifty feature, that everything needed for auth to work is already included. At the same time, if we were to assign security on the custom objects that were added in Salesforce, they would be handled automatically as well.


After signing in, the Finny’s Foods application was displayed, including the five-star rating value for each item.


In a matter of minutes, we were able to create a native application for Android or iOS devices using React Native and the Salesforce Mobile SDK.

Conclusion

Starting in 2021, I have been trying to live by the following mission statement, which I feel can apply to any IT professional:


“Focus your time on delivering features/functionality which extends the value of your intellectual property. Leverage frameworks, products, and services for everything else.”


- J. Vester


In this article, I was able to introduce a custom mobile application to deploy natively from the Android and iOS application stores, using a single collection of source code. Aside from knowing Javascript and understanding the architecture of the React Native framework, no proprietary skills were required.


The Salesforce Mobile SDK certainly adheres to my personal mission statement, which will benefit any feature team that requires Salesforce functionality as part of custom mobile applications running on Android and iOS devices. Software engineers in this realm of development should certainly consider this approach.


If you wish to see the full source code for this article, simply navigate to the following project on GitLab:


https://gitlab.com/johnjvester/finnys-foods


In the next article of the series, I plan to use the Salesforce Mobile SDK with Android Studio to create a native Android application. Once completed, I will perform the same exercise using Xcode for iOS devices.


Have a really great day!


First Published here