Skip to main content

Command Palette

Search for a command to run...

📝 Submit a React Form to Google Sheets using Google Apps Script and Axios

Updated
3 min read
📝 Submit a React Form to Google Sheets using Google Apps Script and Axios

Integrating a React form with Google Sheets is a great way to collect user data without setting up a backend server. In this tutorial, we’ll walk through how to create a basic contact form in React and send that data directly to a Google Sheet using Google Apps Script and Axios.

We’ll not use file uploads here to keep things simple and beginner-friendly.


📦 Prerequisites

  • Basic React knowledge

  • A Google account

  • Node.js and npm installed


🔧 Step 1: Create a Google Sheet

  1. Go to Google Sheets and create a new spreadsheet.

  2. Rename your first row with column headers: Name, Email, Message (or whatever fields you want to collect).


🔌 Step 2: Set Up Google Apps Script

  1. From your Google Sheet, click:

    • ExtensionsApps Script
  2. Delete the default code and paste this:

const sheetName = 'Sheet1'
const scriptProp = PropertiesService.getScriptProperties()

function initialSetup () {
  const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  const lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    const doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    const sheet = doc.getSheetByName(sheetName)

    const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    const nextRow = sheet.getLastRow() + 1

    const newRow = headers.map(function(header) {
      console.log(e)
      // If header is an array, we need to join the values
        if (Array.isArray(e.parameter[header])) {
            return e.parameter[header].join(', ')
        }
        return e.parameters[header].join(",")

    })


    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': e.parameters }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}
  1. Click DeployManage deployments

  2. Click + New deployment

  3. Choose Web app

  4. Set:

    • Execute as: Me (your email)

    • Who has access: Anyone

  5. Click Deploy

  6. Copy the Web App URL — we’ll use this in our React app.


⚛️ Step 3: Build the React App

Create your app (if you haven't):

npx create-react-app react-google-sheet-form
cd react-google-sheet-form
npm install axios

🧑‍💻 Step 4: React Form Component

Create a file called RequestForm.js:

import React, { useState } from "react";
import axios from "axios";

function RequestForm() {
  const [formData, setFormData] = useState({
    Name: "",
    Email: "",
    Message: "",
  });

  const [message, setMessage] = useState("");

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

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await axios.post(
        "YOUR_GOOGLE_APPS_SCRIPT_URL",
        formData
      );

      if (response.data.result === "success") {
        setMessage("Form submitted successfully!");
        setFormData({ Name: "", Email: "", Message: "" });
      } else {
        setMessage("Submission failed.");
      }
    } catch (error) {
      setMessage("Error submitting form.");
    }
  };

  return (
    <div className="form-container">
      <h2>Contact Us</h2>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          name="Name"
          placeholder="Your Name"
          value={formData.Name}
          onChange={handleChange}
          required
        />
        <input
          type="email"
          name="Email"
          placeholder="Your Email"
          value={formData.Email}
          onChange={handleChange}
          required
        />
        <textarea
          name="Message"
          placeholder="Your Message"
          value={formData.Message}
          onChange={handleChange}
          required
        />
        <button type="submit">Submit</button>
      </form>
      {message && <p>{message}</p>}
    </div>
  );
}

export default RequestForm;

🔁 Replace "YOUR_GOOGLE_APPS_SCRIPT_URL" with your actual Google Apps Script deployment URL.


🌐 Step 5: Use the Form Component

In your App.js:

import React from "react";
import RequestForm from "./RequestForm";

function App() {
  return (
    <div className="App">
      <RequestForm />
    </div>
  );
}
export default App;

✅ Done!

Now run your app:

npm start

Fill out the form and submit. Check your Google Sheet — it should now have a new row with your form data!

📝 Submit a React Form to Google Sheets using Google Apps Script and Axios