Submitting Custom Form Data to Google Sheets with React.js

In today’s fast-paced world of web development, efficiently collecting and managing user data is a crucial aspect of many applications. While there are various methods and platforms available, integrating Google Sheets with your React.js application provides a powerful solution for data storage and analysis. In this article, we’ll guide you through the process of submitting custom form data directly to Google Sheets using React.js.

Prerequisites:

Before diving into the implementation, make sure you have the following in place:

  • Working knowledge of React.js.
  • A Google account to create and access Google Sheets.

Setting Up Your React App:

Start by creating a React app using the create-react-app command. Once your app is initialized, clean up unnecessary files to keep your project organized.

npx create-react-app my-google-sheets-app cd my-google-sheets-app

SettingUp the Contact Page for submitting the Form Data.

import React, { useState } from 'react'; import './App.css'; function Contact() {   const [formData, setFormData] = useState({     fullName: '',     email: '',     phoneNumber: ''   });   const handleChange = (e) => {     setFormData({ ...formData, [e.target.name]: e.target.value });   };   const handleSubmit = async(e) => {     e.preventDefault();     console.log('Form submitted:', formData);   };   return (     <div className="App">       <header className="App-header">         <form onSubmit={handleSubmit}>           <div>             <label htmlFor="fullName">Full Name:</label>             <input               type="text"               id="fullName"               name="fullName"               value={formData.fullName}               onChange={handleChange}               required             />           </div>           <div>             <label htmlFor="email">Email:</label>             <input               type="email"               id="email"               name="email"               value={formData.email}               onChange={handleChange}               required             />           </div>           <div>             <label htmlFor="phoneNumber">Phone Number:</label>             <input               type="tel"               id="phoneNumber"               name="phoneNumber"               value={formData.phoneNumber}               onChange={handleChange}               required             />           </div>           <button type="submit">Submit</button>         </form>       </header>     </div>   ); } export default Contact;
Code language: JavaScript (javascript)

Creating the Google Sheets and config AppScript:

1. Open your Google Sheets and add each form input name as a column heading.

2. Navigate to Extensions → App Scripts → Editor → Code.gs and copy the provided script into the script editor.

var sheetName = 'Sheet1'         var scriptProp = PropertiesService.getScriptProperties()         function intialSetup () {           var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()           scriptProp.setProperty('key', activeSpreadsheet.getId())         }         function doPost (e) {           var lock = LockService.getScriptLock()           lock.tryLock(10000)           try {             var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))             var sheet = doc.getSheetByName(sheetName)             var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]             var nextRow = sheet.getLastRow() + 1             var newRow = headers.map(function(header) {               return header === 'timestamp' ? new Date() : e.parameter[header]             })             sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])             return ContentService               .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))               .setMimeType(ContentService.MimeType.JSON)           }           catch (e) {             return ContentService               .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))               .setMimeType(ContentService.MimeType.JSON)           }           finally {             lock.releaseLock()           }         }
Code language: JavaScript (javascript)

3. Save Project,Run and deploy the script.

Make sure you change the access to “Anyone” This will generate a link that you’ll use to post data to the spreadsheet.

After deployment, it looks like:-

Integrating the Google Sheets API with React:

Now, add the function to submit the form data to Google Sheets using the generated API link-

import React, { useState } from 'react'; import './App.css'; function Contact() {   const [formData, setFormData] = useState({     fullName: '',     email: '',     phoneNumber: ''   });   const handleChange = (e) => {     setFormData({ ...formData, [e.target.name]: e.target.value });   };   const handleSubmit = async(e) => {     e.preventDefault();     console.log('Form submitted:', formData);     const data = new FormData();     data.append('fullName', formData.fullName);     data.append('email', formData.email);     data.append('phoneNumber', formData.phoneNumber);    // your URL.     const Sheet_Url="*******************************************************************"     try {       await fetch(Sheet_Url, {         method: 'POST',         body: data,         muteHttpExceptions: true,       });       setFormData({         fullNameame: '',         email: '',         phoneNumber: '',       });     } catch (error) {       console.log(error);     }   };   return (     <div className="App">       <header className="App-header">         <form onSubmit={handleSubmit}>           <div>             <label htmlFor="fullName">Full Name:</label>             <input               type="text"               id="fullName"               name="fullName"               value={formData.fullName}               onChange={handleChange}               required             />           </div>           <div>             <label htmlFor="email">Email:</label>             <input               type="email"               id="email"               name="email"               value={formData.email}               onChange={handleChange}               required             />           </div>           <div>             <label htmlFor="phoneNumber">Phone Number:</label>             <input               type="tel"               id="phoneNumber"               name="phoneNumber"               value={formData.phoneNumber}               onChange={handleChange}               required             />           </div>           <button type="submit">Submit</button>         </form>       </header>     </div>   ); } export default Contact:
Code language: JavaScript (javascript)

After submitting the form, the updated sheet looks like this:-

Check out our other trending blog post: How to implement infinite scroll in react?

Conclusion:

By following these steps, you have successfully set up a React.js application to submit custom form data directly to Google Sheets. This streamlined integration enhances data collection efficiency and provides a seamless user experience. Feel free to modify the styling and adapt the code to suit your specific needs.

Recent Post

  • Generative AI in HR Operations: Overview, Use Cases, Challenges, and Future Trends

    Overview Imagine a workplace where HR tasks aren’t bogged down by endless paperwork or repetitive chores, but instead powered by intelligent systems that think, create, and adapt—welcome to the world of GenAI. Generative AI in HR operations offers a perfect blend of efficiency, personalization, and strategic insight that transforms how organizations interact with their talent. […]

  • Generative AI in Sales: Implementation Approaches, Use Cases, Challenges, Best Practices, and Future Trends

    The world of sales is evolving at lightning speed. Today’s sales teams are not just tasked with meeting ambitious quotas but must also navigate a maze of complex buyer journeys and ever-rising customer expectations. Despite relying on advanced CRM systems and various sales tools, many teams remain bogged down by repetitive administrative tasks, a lack […]

  • Generative AI in Due Diligence: Integration Approaches, Use Cases, Challenges, and Future Outlook

    Generative AI is revolutionizing the due diligence landscape, setting unprecedented benchmarks in data analysis, risk management, and operational efficiency. By combining advanced data processing capabilities with human-like contextual understanding, this cutting-edge technology is reshaping traditional due diligence processes, making them more efficient, accurate, and insightful. This comprehensive guide explores the integration strategies, practical applications, challenges, […]

  • Exploring the Role of AI in Sustainable Development Goals (SDGs)

    Artificial Intelligence (AI) is revolutionizing how we address some of the world’s most pressing challenges. As we strive to meet the United Nations’ Sustainable Development Goals (SDGs) by 2030, AI emerges as a powerful tool to accelerate progress across various domains. AI’s potential to contribute to sustainable development is vast from eradicating poverty to combating […]

  • Future Trends in AI Chatbots: What to Expect in the Next Decade

    Artificial Intelligence (AI) chatbots have become indispensable across industries. The absolute conversational capabilities of AI chatbots are enhancing customer engagement, streamlining operations, and transforming how businesses interact with users. As technology evolves, the future of AI chatbots holds revolutionary advancements that will redefine their capabilities. So, let’s start with exploring the AI chatbot trends: Future […]

  • Linguistics and NLP: Enhancing AI Chatbots for Multilingual Support

    In today’s interconnected world, businesses and individuals often communicate across linguistic boundaries. The growing need for seamless communication has driven significant advancements in artificial intelligence (AI), particularly in natural language processing (NLP) and linguistics. AI chatbots with multilingual support, are revolutionizing global customer engagement and service delivery. This blog explores how linguistics and NLP are […]

Click to Copy