• Twilio can be a lot of fun. It has a robust API that lets you send text messages. I worked on a side project that involved scheduling text messages in a ReactJS app. I'm not a developer by trade, just an enthusiast, so I ran into some challenges using Twilio's API to send messages from a React component. Many of these problems would be trivial for a seasoned developer, but if you're a beginner like me, you might find this information helpful. 

    In this tutorial, I'll show you what a basic Twilio-ReactJS integration looks like. The difficulty level of this tutorial is beginner to intermediate.

    What we'll be using:

    • ReactJS (naturally)
    • Express
    • Your typical combination of NPM and Webpack

    We'll need the node package fetch on the client-side, and the packages body-parser and twilio for the backend.

    Before we get started, here's a link to the Github repository for a barebones Twilio/React integration.

    Overall Strategy

    We don't want to make client-side HTTP requests to Twilio because that would expose our Twilio API keys.

    Therefore, we pass information from the client to the server, and then make the HTTP requests to Twilio server-side.

    For this example, we'll use Express to make the final API request to Twilio from our ReactJS app.

    Express describes itself as:

    A minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

    So Express is like a layer that sits on top of Node.js.

    Sending Data from Our React Component to The Server (Express)

    We'll use fetch (npm install whatwg-fetch --save) to make web requests within our ReactJS components. Here's an example to get you started:

    fetch('/sendsms', {
      method: 'POST',
      headers: {
        Accept: 'application/JSON',
        'Content-Type': 'application/JSON'
      },
      body: JSON.stringify({"data": this.state.data})
    })

    If you want to see this in context, here's the file on github.

    As you can see, with fetch, the pattern is fairly straightforward: 

    fetch(url, { method, headers, body })

    Fetch is invoked inside a ReactJS component. For this example, I invoked it inside a function sendSms() that was called when a button was pressed:

    <button onClick={this.sendSms.bind(this)}>Send SMS</button>

    In this case, fetch posts data to the relative endpoint /sendsms. When we configure our server with Express, we'll define this endpoint and use Twilio's node package (npm install twilio --save) to make the final request to Twilio.

    To pass data via fetch, use this.state.myData. Don't forget to send the data stored in state as a JSON by calling JSON.stringify({...})

    Setting Up Express

    Here's what our full express configuration file server.js looks like:

    import express from 'express';
    import path from 'path';
    import keys from './twiliokeys';
    import bodyParser from 'body-parser';
    
    const app = express();
    
    app.use('/', express.static('public'));
    
    app.post('/sendsms', bodyParser.json(), (req, res) => {
      var client = require('twilio')(keys.sid, keys.token);
      client.sendMessage({
        to: req.body.data,
        from: '+12223334444',
        body: 'word to your mother.'
      }, function (err, responseData) {
        if (!err) {
          res.json({"From": responseData.from, "Body": responseData.body});
        }
      })
    })
    
    app.listen(process.env.PORT || 3000);

    Here's a link to the file on Github.

    • <code>import keys from './twilioKeys';</code>. I stored my twilio API keys in a separate file called <code>twilioKeys.js</code>
    • <code>app.use('/', express.static('public'));</code> - This tells Express what to do with requests to localhost:3000/. I set this to 'public' because that's the location of my built ReactJs application.
    • <code>app.post('/sendsms', bodyParser.json(), (req, res) => {}); </code> This tells the server how to handle post requests to the /sendsms endpoint. This was the endpoint we told fetch to send data to in our ReactJs component.
    • <code>var client = require('twilio')(keys.sid, keys.token);</code> Here we require the Twilio node package. <code>require('twilio')</code> actually returns a function that takes the twilio SID and Auth Token as arguments.
    • <code>client.sendMessage({to, from, body})</code> This is where you'd include the sender and recipient's phone numbers as well as the body of the text message.
    • <code>req.body.data</code> What does this mean? When we send a JSON using fetch from our react component, we need req.body refers to the body of the POST request. So if we had a JSON like <code>{"food": "apple"}</code>, then we could write <code>req.body.food</code> to return "apple."