Example to Send Text SMS on Button Click in React Native

Introduction

Here is an Example to Send Text SMS on Button Click in React Native. Instead of remembering or copying the number to send the Text SMS you can provide one tab send SMS experience to the users of your application.

We will use react-native-sms package for this example.

You can also visit Make Phone Call, Send SMS or Email Using React Native Communication using react-native-communications to make Phone Calls, Send Text SMS, Send Email and Open a URL in Browser.

You can also see:

  1. React Native Share API to Share TextInput message
  2. Share Facebook Post with URL from React Native App
  3. Send WhatsApp Message from React Native App
  4. Tweet on Twitter with URL from React Native App

To Send SMS

SendSMS.send(
  {
    // Message body
    body: bodySMS,
    // Recipients Number
    recipients: [mobileNumber],
    // An array of types 
    // "completed" response when using android
    successTypes: ['sent', 'queued'],
  },
  (completed, cancelled, error) => {
    if (completed) {
      console.log('SMS Sent Completed');
    } else if (cancelled) {
      console.log('SMS Sent Cancelled');
    } else if (error) {
      console.log('Some error occured');
    }
  },
);

In this example of sending a Text SMS from React Native App, we will send the SMS by clicking on a button using  react-native-sms library. So let’s get started.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependency

To use SendSMS we need to install react-native-sms package. To install this

Open the terminal and jump into your project

cd ProjectName

Run the following command

npm install react-native-sms --save

This command will copy all the dependencies into your node_module directory.

CocoaPods Installation

After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but need to install pods. So to install pods use

cd ios && pod install && cd ..

Permission to Send SMS for Android

We are trying to use the SMS feature so we need to add some permission in AndroidManifest.xml file for Android. For more about the permission, you can see this post.

So we are going to add the following permissions in the AndroidMnifest.xml

<uses-permission android:name="android.permission.READ_SMS"/>

Here we have done all the configurations we need.

Code to Send Text SMS

Now open App.js in any code editor and replace the code with the following code

App.js

// Example to Send Text SMS on Button Click in React Native
// https://aboutreact.com/send-text-sms-in-react-native/

// import React in our code
import React, {useState} from 'react';

// import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  TextInput,
} from 'react-native';

// import SMS API
import SendSMS from 'react-native-sms';

const App = () => {
  const [mobileNumber, setMobileNumber] = useState('9999999999');
  const [bodySMS, setBodySMS] = useState(
    'Please follow https://aboutreact.com',
  );

  const initiateSMS = () => {
    // Check for perfect 10 digit length
    if (mobileNumber.length != 10) {
      alert('Please insert correct contact number');
      return;
    }

    SendSMS.send(
      {
        // Message body
        body: bodySMS,
        // Recipients Number
        recipients: [mobileNumber],
        // An array of types 
        // "completed" response when using android
        successTypes: ['sent', 'queued'],
      },
      (completed, cancelled, error) => {
        if (completed) {
          console.log('SMS Sent Completed');
        } else if (cancelled) {
          console.log('SMS Sent Cancelled');
        } else if (error) {
          console.log('Some error occured');
        }
      },
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.container}>
        <Text style={styles.titleText}>
          Example to Send Text SMS on Button Click in React Native
        </Text>
        <Text style={styles.titleTextsmall}>
          Enter Mobile Number
        </Text>
        <TextInput
          value={mobileNumber}
          onChangeText={
            (mobileNumber) => setMobileNumber(mobileNumber)
          }
          placeholder={'Enter Conatct Number to Call'}
          keyboardType="numeric"
          style={styles.textInput}
        />
        <Text style={styles.titleTextsmall}>
          Enter SMS body
        </Text>
        <TextInput
          value={bodySMS}
          onChangeText={(bodySMS) => setBodySMS(bodySMS)}
          placeholder={'Enter SMS body'}
          style={styles.textInput}
        />
        <TouchableOpacity
          activeOpacity={0.7}
          style={styles.buttonStyle}
          onPress={initiateSMS}>
          <Text style={styles.buttonTextStyle}>
            Send Message
          </Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    padding: 10,
    textAlign: 'center',
  },
  titleText: {
    fontSize: 22,
    textAlign: 'center',
    fontWeight: 'bold',
  },
  titleTextsmall: {
    marginVertical: 8,
    fontSize: 16,
  },
  buttonStyle: {
    justifyContent: 'center',
    marginTop: 15,
    padding: 10,
    backgroundColor: '#8ad24e',
  },
  buttonTextStyle: {
    color: '#fff',
    textAlign: 'center',
  },
  textInput: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    width: '100%',
    paddingHorizontal: 10,
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

To run the project on an Android Virtual Device or on real debugging device

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Download Source Code

FAQ:
1. How to send a Text without having to press the send message button?
2. How can I send the message directly from my react native application without opening the default message app?
Ans: Sorry but this is not possible with this example. This is a cross platform example which does not provide the same, you need to manage some native logic to do that.

Output Screenshots

react_native_send_sms1    react_native_send_sms2

This is how you can send SMS in React Native. If you have any doubt or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂


Related Posts

19 thoughts on “Example to Send Text SMS on Button Click in React Native”

  1. Hi thank you so much for the detailed tutorial. I am trying to use this to send a message to multiple recipients and I am trying to pass multiple recipients as an array ( recipients: [‘0123456789’, ‘9876543210’],) but for some reason on Android it opens the message compose screen with just the first number. Do you by any chance know how I can include multiple recipients?

    Reply
    • Thank You for your appreciation it will motivate me to do more.
      I have tried it and it works for my device. I think its device-dependent as you can see in the following code snippet from the library it is just taking the recipients and adding a separator semicolon(;) and comma (;) for the Samsung device only. So it depends on the device which type of separator device want. Like if the library added comma and device needs semicolon as separator then the device took all the contacts as a string and will take all numbers as a single number.
      You can find more details about it on this thread.

      Library code snipet:

      
      Intent sendIntent;
      sendIntent = new Intent(Intent.ACTION_SENDTO);
      String recipientString = "";
      if (recipients != null) {
          //Samsung for some reason uses commas and not semicolons as a delimiter
          String separator = ";";
          if(android.os.Build.MANUFACTURER.equalsIgnoreCase("Samsung")){
              separator = ",";
          }
      
          for (int i = 0; i < recipients.size(); i++) {
              recipientString += recipients.getString(i);
              recipientString += separator;
          }
      }
      sendIntent.setData(Uri.parse("smsto:"+recipientString));  // This ensures only SMS apps respond
      sendIntent.putExtra("sms_body", body);
      sendIntent.putExtra("exit_on_sent", true);           
      reactContext.startActivityForResult(sendIntent, REQUEST_CODE, sendIntent.getExtras());
      

      I'll try to find a permanent solution for all the devices. Meanwhile, if you find any solution then please share for others too. 🙂

      Reply
  2. Hi!
    This tutorial is great! Thanks!
    I was wondering though if you have a version for API levels higher than 23? (I’m targeting higher API devices, but I don’t want to ask for permission everytime the send button is clicked.)

    Thank you for your time!
    Moore

    Reply
    • It will ask for the one time only and will check next time if the permission is provided then it will ignore and will proceed and if user disabled the permission for the app in between then will ask for the permission again.

      Reply
  3. Hi,
    This tutorial is great. It helped me a lot.
    I have one question, please help. Is it possible to close the message screen automatically once text is sent? I am new to React-native, so not sure if my question is relevant here.
    Thanks

    Reply
    • Nice to hear that it helped you..
      In react native we are just triggering the message app with some data not controlling it.. So it is not posible in current case. May be you have to integrate some native code for that.

      Reply
  4. Sir how msg will be sent without moving to mobile sms messenger,i want msg should directly sent from react native app,without opening mobile sms messange

    Reply
  5. The permission which used here is sensitive user information of the user. Also if I send for review most probably it get rejected. Any solution for this? Or what is your concern here?

    Reply
  6. I keep getting the list of recipients on my phone show up when I have a single recipients for the property its not pulling that number w body, its showing a list of contacts.

    Any idea why?

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.