Thought leadership from the most innovative tech companies, all in one place.

How to Send WhatsApp Messages From Your React App Easily

A very simple way to send messages on WhatsApp web in React.

Photo by Alexander Shatov on UnsplashPhoto by Alexander Shatov on Unsplash

Intro:

Ever wondered how to send WhatsApp messages from your React app without using the Whatsapp API?

In this article, we will explore a very simple way to send messages on the WhatsApp web in React.

Applications of sending WhatsApp messages:

  1. Communicate with customers.

  2. Auto text messages.

Requirements: Level — Beginner

  1. JavaScript basics

  2. Node.js basics

Check out the app: Send Whatsapp Messages Simple web app to send messages from React to Whatsappwhatsapp-react-messages.herokuapp.com

With the formalities out of the way, let’s get started!

Starters:

Clone this repo to get the basic code. After cloning use the npm i command in your terminal to install the required dependencies.

After cloning and installing, use npm run start to start the app.

image

This is what you’ll see after opening localhost:3000.

Note: The designing, validation, and styling of the project have already been done as the focus of this article is to learn how to send messages only.

Getting Acquainted:

image

The following is what your screen will look like after running the React script.

The files are as follows:

  1. *index.js: *Used to load the 'App' component into the HTML element with id ‘root’ in the index.html file.

  2. *App.css: *Style sheet of the app.

  3. *App.js: *Main container component in React.

  4. *components *folder: Folder containing all the components which the user will interact with.

  5. SendMessage.js: Main file which we will be interacting with.

  6. *layout *folder: Creator credentials and footer (Need not change).

Folder StructureFolder Structure

Details of the SendMessage.js Component:

const SendMessages = () => {
  const CHARACTER_LIMIT = 100;

  const [numberEmptyError, setNumberEmptyError] = useState(false);
  const [messageEmptyError, setMessageEmptyError] = useState(false);

  const [formData, setFormData] = useState({
    mobileNumber: "",
    message: "",
  });

  const { mobileNumber, message } = formData;

  const onChange = (e) => {
    e.preventDefault();
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

  const onSubmit = (e) => {
    e.preventDefault();
    if (mobileNumber.length < 1) {
      setNumberEmptyError(true);
      setTimeout(() => setNumberEmptyError(false), 3000);
    } else if (message.length < 1) {
      setMessageEmptyError(true);
      setTimeout(() => setMessageEmptyError(false), 3000);
    } else {
      // TODO: Enter code here
    }
  };

  return (
    <div className="communication">
      <div className="whatsapp-card app">
        <div className="title flex_middle">
          <div style={{ marginRight: "0.5em" }}>
            <WhatsAppIcon />
          </div>
          <div>Send Message</div>
        </div>
        {numberEmptyError && (
          <div className="errors">Mobile number cannot be empty!</div>
        )}
        {messageEmptyError && (
          <div className="errors">Message cannot be empty!</div>
        )}
        {!numberEmptyError && !messageEmptyError && (
          <div className="errors-null">.</div>
        )}
        <div className="search_contact app">
          <CssTextField
            error={numberEmptyError}
            label="Mobile Number"
            placeholder="Mobile Number"
            name="mobileNumber"
            value={mobileNumber}
            onChange={onChange}
            size="small"
            style={{
              margin: "1em 0em",
            }}
            inputProps={{
              style: textFieldStyle,
            }}
            InputLabelProps={{
              style: textFieldInputLabelStyle,
            }}
            required
          />
        </div>
        <div className="message app" style={{ marginTop: "1.5em" }}>
          <CssTextField
            multiline
            maxRows={4}
            label="Message"
            placeholder="Hi! Sending a message from React...."
            size="small"
            InputLabelProps={{
              style: textFieldInputLabelStyle,
            }}
            inputProps={{
              style: {
                width: "230px",
                height: "90px",
              },
              maxLength: CHARACTER_LIMIT,
            }}
            FormHelperTextProps={{
              style: {
                margin: 0,
                padding: "0 0 0 5px",
                fontSize: 10,
              },
            }}
            name="message"
            value={message}
            onChange={onChange}
            required
            error={message.length > CHARACTER_LIMIT - 1 || messageEmptyError}
            helperText={
              !(message.length > CHARACTER_LIMIT - 1)
                ? `${message.length}/${CHARACTER_LIMIT}`
                : "Max length exceeded"
            }
          />
        </div>
        <div style={{ marginTop: "1.5em" }}>
          <Button
            onClick={onSubmit}
            variant="outlined"
            color="success"
            size="small"
          >
            Send
          </Button>
        </div>
      </div>
    </div>
  );
};

The API to send messages through WhatsApp web is as follows:

https://web.whatsapp.com/send?phone=number&text=message&app_absent=0

So, we use the text fields to capture the number and message which we will append to the URL. It is important to include the country code when entering the mobile number.

image

On clicking the ‘*Send’ *button we invoke the ‘*onSubmit’ *function which validates if the message length and the mobile number length are greater than one so that empty texts are not sent.

If all is well then we call the *window.open() *method with the URL to open Whatsapp in a new tab which will open the chat of the person to whom the number we have entered belongs.

Generating the URL:

In the *else *section of the *onSubmit *function, we will use regex to remove all characters of the number which are not alphanumeric and then append the mobile number to the URL.

const onSubmit = (e) => {
  e.preventDefault();
  if (mobileNumber.length < 1) {
    setNumberEmptyError(true);
    setTimeout(() => setNumberEmptyError(false), 3000);
  } else if (message.length < 1) {
    setMessageEmptyError(true);
    setTimeout(() => setMessageEmptyError(false), 3000);
  } else {
    // Regex expression to remove all characters which are NOT alphanumeric
    let number = mobileNumber.replace(/[^\w\s]/gi, "").replace(/ /g, "");

    // Appending the phone number to the URL
    let url = `https://web.whatsapp.com/send?phone=${number}`;
  }
};

Similarly, append the message to the URL after encoding it.

const onSubmit = (e) => {
  e.preventDefault();
  if (mobileNumber.length < 1) {
    setNumberEmptyError(true);
    setTimeout(() => setNumberEmptyError(false), 3000);
  } else if (message.length < 1) {
    setMessageEmptyError(true);
    setTimeout(() => setMessageEmptyError(false), 3000);
  } else {
    // Regex expression to remove all characters which are NOT alphanumeric
    let number = mobileNumber.replace(/[^\w\s]/gi, "").replace(/ /g, "");

    // Appending the phone number to the URL
    let url = `https://web.whatsapp.com/send?phone=${number}`;

    // Appending the message to the URL by encoding it
    url += `&text=${encodeURI(message)}&app_absent=0`;
  }
};

Finally, a new tab will be opened in the browser which will redirect to WhatsApp web and open the chat of the person with the entered phone number and the message to be sent.

const onSubmit = (e) => {
  e.preventDefault();
  if (mobileNumber.length < 1) {
    setNumberEmptyError(true);
    setTimeout(() => setNumberEmptyError(false), 3000);
  } else if (message.length < 1) {
    setMessageEmptyError(true);
    setTimeout(() => setMessageEmptyError(false), 3000);
  } else {
    // Regex expression to remove all characters which are NOT alphanumeric
    let number = mobileNumber.replace(/[^\w\s]/gi, "").replace(/ /g, "");

    // Appending the phone number to the URL
    let url = `https://web.whatsapp.com/send?phone=${number}`;

    // Appending the message to the URL by encoding it
    url += `&text=${encodeURI(message)}&app_absent=0`;

    // Open our newly created URL in a new tab to send the message
    window.open(url);
  }
};

That's it!

Conclusion

In this article, we saw how to send messages from a React app to Whatsapp

Link with a working example:

Send Whatsapp Messages

Cheers!




Continue Learning