How To Create A Survey Application Using Strapi And React.JS

Strapi logo
  • Product

    • Code.svgCreate APIsDesign REST and GraphQL Content Delivery APIs to connect to any frontend.
    • Layout.svgContent ManagementCraft experiences and easily manage editing, publishing, and translation.
    • PencilRuler.svgCustomizationPersonalize your CMS to meet your project's unique requirements.
    • UsersThree.svgCollaborationWork together easily on code and content.
    • Vector.svgHostingHost your projects on robust, secure servers in minutes.
    • Lock.svgSecurityImplement robust security measures to protect your information.
    • sparkle_fill_d74ee2b638.svgStrapi AIAutomate Content Modeling, Translations & more
    • Cloud.svgCloudPaaS hosting for Strapi projects.
    • Buildings.svgEnterprise EditionA self hosted, Enterprise-ready Edition.
    • ShoppingCart.svgStrapi MarketMarketplace of plugins and integrations.
    • Lightning.svgFeaturesDiscover all the features available in Strapi today.
  • Solutions

    • Globe.svgWebsitesManage your brand narrative.
    • Code (2).svgBackend Framework Build, customize, and scale backends.
    • DeviceMobile.svgMobile AppsOne CMS, any devices.
    • Basket.svgE-commerceLevel up your eCommerce experiences
    • Code.svgDevelopersIntegrate Strapi with your favorite tools
    • Feather.svgContent ManagersManage Content Autonomously
    • Briefcase.svgBusiness leadersUnlock the benefit of structured content
    • medal-fill.svgDigital AgenciesAccelerate project delivery and provide a Client-Friendly Content Editing
    • Coins.svgFinancial ServicesBuild trustful relations with your customers
    • HeadCircuit.svgTech and Business ServicesStand out with exceptional B2B content.
    • Megaphone.svgTelco, Media, and GamingCreate and manage content on any platform
  • Developers

    • Article.svgBlogLatest Strapi news & updates
    • Handshake.svgPartnersFind official partner or become one
    • Confetti.svgCase studiesDiscover who uses Strapi
    • Code.svgOpen SourceContribute & collaborate on GitHub
    • ChatsCircle.svgForumDiscuss, ask questions and find answers
    • ChatsCircle.svgDiscordDiscuss, ask question and find answers
    • Play.svgVideo TutorialsDiscuss, ask question and find answers
    • Calendar.svgEventsUpcoming and On-demand Events
    • Vector (6).svgStrapi GoodiesDiscover the latest Strapi goodies
  • Docs

  • Pricing

  • Cloud

    • Cloud.svgDiscover Strapi CloudPaaS hosting for Strapi projects
    • SignIn.svgLogin to Strapi CloudLogin or Sign up for Strapi Cloud.
    • Book.svgStrapi Cloud DocsStrapi Cloud hosting technical documentation
  • Latest articles
  • Company
  • Engineering
  • Tutorials
  • Ecosystem
SubscribeNewsletter Icon
  • Last updated: December 8, 2022 (Strapi v4 era)
  • 12 min read
Creating a Survey Application Using Strapi and React.JSStrapi v4ozb0xyjgtbkaksq2ddyb.jpg

Popoola Temitope

July 12, 2022

tweet selectionChibuike Nwachukwu.png

Survey applications are software that companies use to get feedback from customers or employees on how well their products or services are performing. Because organizations can obtain customer or employee reviews of their services, survey applications play an important role in organization service analysis. The company will then work on the collected feedback to provide the best services that suit the expectations of the customers.

Many companies use surveys because it is one of the easiest ways to collect information from the outside world. Whether your company wants to collect opinions or wants you to complete a feedback form, a web survey is a good way to go.

Surveys can show you the problems your service solves (and the ones it doesn't) and give you insight into what you need to be doing to satisfy your customers. They'll show you more about your pricing schemes and tell you how you can improve based on what your customers say. In short, surveys should be built into every organization's strategy to get feedback from customers and prospects as well as a way to build trust with them.

In this tutorial, I'll walk you through the steps of creating a survey app with React.js using Strapi as the backend tool. Here's what it'll look like:

Survey Application

Prerequisites

To follow this tutorial, you should have:

  • Node.js v14 or v12 installed on your computer. To check your node version, use the node -v command.
  • NPM or Yarn installed on your computer.
  • Basic knowledge of React.js.

What is Strapi?

Strapi is an open-source Content API Framework that is used to build content-oriented applications. It can be used to build a simple blog or used to build complex e-commerce platforms like Shopify.

Strapi is written in Node.js and uses MongoDB as its database. It provides a rich set of features, including authentication and authorization, content management, data import/export, performance monitoring, etc.

What is React.js?

React.js is a library for creating user interfaces. It's a declarative, component-based UI library. It allows you to create reusable UI components that render using data models to describe how the component should be rendered.

React aims to address one problem: building large applications with data that changes over time. We want our apps to be fast and responsive no matter how much data they display or how many things happen on the page at once, so we need an efficient way of updating the view when data changes.

Why is A Survey Application Important?

There are many reasons why developers need to use surveys. 1. They can get feedback from their customers about their products. 2. They can know what features people want and how they want them implemented. 3. It helps them improve the quality of their product and make changes accordingly. 4. It also gives them an idea about the market share of their product, which will help them decide whether it is worth investing more time into the development process or not.

Features of Our Survey Application

The survey application that we will create will have the following features:

  • Random questions
  • 'Yes or No' questions
  • Localized questions
  • Form questions

Strapi Installation

Let's kick-start with our installation. Open the command line, and enter one of the following commands:

  • Yarn command:
yarn create strapi-app survey-app --quickstart

Or

  • npx command:
npx create-strapi-app survey-app --quickstart

The above command will install all the needed packages for the project. After the installation, the Strapi app will automatically be launched in the browser. Register with your details and it will take you to your dashboard page as shown below:

Strapi Dashboard

React.js Installation

Creating a React app is easy. The first step is to run the following commands on the terminal:

npx create-react-app my-app cd my-app npm start

The above command will create a directory for your new project and initialize it as a package. The React app must be installed under the my-project folder.

Building the Survey App

Now that we have done all the prep, let's dive right into building our survey app.

Creating Our App Collections on Strapi

In this simple survey app, we’ll create two content types named survey and response.

  • Survey Collection Type:

This collection type will contain all the survey questions with their options so that users can choose that response. We’ll also use an internationalization plugin to translate the survey questions into different languages.

Before we create the survey collection, let's add a new locale language to our application. To do this is simple. From your dashboard menu, click on Settings. Then, under the global settings sub-menu, click on internationalization.

To add the new language, click on the "add new locale" button and then select the language and save it. But for our survey application we’ll only add French (Canada) fr-CA, as shown below:

how to create internationalization in Strapi

Now, let's create the survey collection type. From your dashboard menu, click on Content-Type Builder, then click on Create New Collection Type. Enter the display name for the collection type and then click on advanced settings. Under advanced settings, make sure that you enable international and click on continue.

creating collection type in strapi

After that, we’ll add the necessary fields for the survey content type. The survey content type fills in the following fields: i. question: (Text - Long Text) ii. a: (Text - Short Text) iii. b: (Text - Short Text) iv. c: (Text - Short Text)

Creating fields in strapi

  • Response Collection Type:

This collection type is where all the survey responses will be stored. The response collection type will contain the following fields: Email, surveyQuestion, surveyResponse. To create the response collection type, follow the same steps as used in the survey collection type above.

Creating fields in strapi

Adding Questions to the Survey Collection

Let's add some of the survey questions to the survey collection type. To do this is simple. From the content manager menu, click on survey and then click the "Create new entry" button. Fill in the survey questions and their response options, then save it and click on publish. You can add as many survey questions as you like.

how to create new record in strapi

Adding Internationalization Questions

To add locale content for the survey collection type, on the survey collection page, click on the edit icon for each question. From the left-hand side, click on locale and select your preferred language. Fill in the survey question in the selected language, save and publish it.

how to publish locale content in strapi

Wrapping up the Backend

Before we move to frontend design, we need to ensure that survey and response content types are available via API call. Go to Settings, click Roles, and edit Public. Select all and click on save for both survey and response respectively.

Now we can make requests to survey and response collection types using http://localhost:1337/api/surveys/ and http://localhost:1337/api/responses/ restful endpoint from the front-end interface.

Strapi API Permission

Building the Frontend

In this tutorial, we’ll not focus on the styling, but from your React project, open app.css and replace the styling with the following code:

1// src/App.css2.App{3 text-align: center;4}5 6.main{7width:99%;8height: 500px;9 background-color: #e7e7e7;10 border-radius: 10px;11 margin-top: 70px;12border: 4px solid #f3f3f3 13}14 15.bar1{16width:100%;17height: 70px;18 border-top-right-radius: 10px;19 border-top-left-radius: 10px;20}21 22.bar2{23width:70%;24height: 27px;25 background-color: white;26 border-radius: 10px;27}28 29.bar3{30width:100%;31height: 27px;32 background-color: #f68e56;33float: left;34 border-radius: 10px;35color: white;36}37 38 #surv {39 40width:90%;41height: 380px;42 background-color: #f3f3f3;43 border-top-right-radius: 10px;44 border-top-left-radius: 10px;45 margin-left: 70px;46}47 48.divid1{49height: 200px;50width: 440px;51float: left;52 margin-left: 200px;53}54 55.divid2{56height: 200px;57width: 440px;58float: right;59}60 61.input{62border: 2px solid #d5d5d5;63 font-size: 17px;64background: #fbfbfb;65height: 20px;66padding: 8px;67width: 400px;68}69 70.radio_option{71width: 1100px;72height: 430px;73 margin-left: 100px;74}75 76.radio{77border: 2px solid #d5d5d5;78 font-size: 17px;79background: #fbfbfb;80height: 24px;81padding: 8px;82width: 24px;83}84.checkbox{85border: 2px solid #d5d5d5;86 font-size: 17px;87background: #fbfbfb;88height: 24px;89padding: 8px;90width: 24px;91}92 93.container{94width: 1100px;95height: 430px;96}97 98.hid{99display: none;100width:90%;101height: 380px;102 background-color: #f3f3f3;103 border-top-right-radius: 10px;104 border-top-left-radius: 10px;105 margin-left: 70px 106}107 108.view{109display: inherit;110width:90%;111height: 380px;112 background-color: #f3f3f3;113 border-top-right-radius: 10px;114 border-top-left-radius: 10px;115 margin-left: 70px 116}117 118.btn{119width: 100px;120height: 32px;121 background-color: #f68e56;122 border-radius: 100px;123}

What Is Axios?

Axios is a tool to make HTTP requests and handle the responses. It's written on top of the Promise API and can be used in both the browser and on the server. It's fast, simple, and supports features like caching, timeout, and authentication.

We'll be using Axios to make requests to our Strapi project endpoint because of its capabilities and features. Let's get Axios up and running in our React app.

Axios Installation

To install Axios, navigate to your React project folder in the terminal and run the command below.

npminstall Axios

Building the Application's Functionality

To add functionality to our project, open app.js in your code editor and paste in the following code, then save it.

1// src/App.js2importReact,{ useState, useEffect }from'react';3importaxiosfrom'axios';4import'./App.css';5 6functionApp(){7const[email, setemail]=useState('2');8const[gender, setgender]=useState('3');9const[question1, setQuestion1]=useState("");10const[question2, setQuestion2]=useState("");11const[question3, setQuestion3]=useState("");12const[response1, setResponse1]=useState("");13const[response2, setResponse2]=useState("");14const[response3, setResponse3]=useState("");15const[lang, setLang]=useState("en");16const[QuestionNum1, setQuestionNum1]=useState(1);17const[QuestionNum2, setQuestionNum2]=useState(2);18const[button, setButton]=useState("Start Survey");19constgetsurvey=async(value)=>{20 21letTasks=await axios.get('http://localhost:1337/api/surveys?locale='+ value);22setQuestion1(Tasks.data.data\[0\]["attributes"]);23setQuestion2(Tasks.data.data\[QuestionNum1\]["attributes"]);24setQuestion3(Tasks.data.data\[QuestionNum2\]["attributes"]);25setQuestionNum1(prev=>QuestionNum1+2);26setQuestionNum2(prev=>QuestionNum2+2);27}28 29 30 31constload=(value)=>{32getsurvey(value);33}34 35const[checkbox, setCheckbox]=useState({box1:"",box2:"",box3:""});36 37 38constupdateBox=(box, value)=>{39if(box ==="1"){40if(checkbox.box1=== value){41 value =""42}43setCheckbox(previousState=>{44 45return{...previousState,box1: value }46 47});48 49}50 51if(box ==="2"){52if(checkbox.box2=== value){53 value =""54}55setCheckbox(previousState=>{56return{...previousState,box2: value }57});58}59if(box ==="3"){60if(checkbox.box3=== value){61 value =""62}63setCheckbox(previousState=>{64return{...previousState,box3: value }65});66}67}68 69 70 71const[page, setpage]=useState(0);72const[page0, set0page]=useState('view');73const[page1, set1page]=useState('hid');74const[page2, set2page]=useState('hid');75const[page3, set3page]=useState('hid');76const[page4, set4page]=useState('hid');77 78constaddTask=async(quest, valu)=>{79let res =await axios 80.post("http://localhost:1337/api/responses/",{81 82"data":{"Email": email,"surveyQuestion": quest,"surveyResponse": valu}83})84 85.catch((err)=>console.log(err));86 87};88 89useEffect(()=>{90setResponse3(prev=> checkbox.box1+","+ checkbox.box2+","+ checkbox.box3);91},[checkbox])92 93 94constnext=()=>{95if(page ===0){96set0page(prev=>"hid");97set1page(prev=>"view");98setpage(prev=> page +1);99setButton(prev=>"Next Question");100}101if(page ===1){102set1page(prev=>"hid");103set2page(prev=>"view");104setpage(prev=> page +1);105setButton(prev=>"Next Question");106}107if(page ===2){108set2page(prev=>"hid");109set3page(prev=>"view");110setpage(prev=> page +1);111setButton(prev=>"Submit");112}113if(page ===3){114set3page(prev=>"hid");115set4page(prev=>"view");116setpage(prev=>4);117setButton(prev=>"New Survey");118addTask(question1.question, response1);119addTask(question2.question, response2);120addTask(question3.question, response3);121getsurvey(lang);122}123if(page ===4){124set4page(prev=>"hid");125set2page(prev=>"view");126setpage(prev=>2);127setButton(prev=>"Next Question");128}129}130return(131<div className="App">132<div className="main">133<div className="bar1">134<center>135<span>Progress</span>136<div className="bar2">137<div className="bar3">138{page}/3139</div>140</div>141</center>142</div>143<div id="surv" className={page0}>144 145<br />146<h2>welcome to my survey app</h2>147<div className="container">148<div className="divid1">149<br />150<input type="text" className="input" name="" placeholder="Email address" onChange={(event)=>setemail(event.target.value)}/>151<br /><br />152<label>SelectLanguage</label>153<select className="input" onChange={(event)=>load(event.target.value)} placeholder="Select Language">154<option>SelectLanguage</option>155<option value="en">English</option>156<option value="fr-CA">French</option>157</select>158<br />159<br />160</div>161<div className="divid2">162<br />163<input type="text" className="input" name="" placeholder="Gender" onChange={(event)=>setgender(event.target.value)}/>164<br /><br />165</div>166</div>167</div>168<div id="surv" className={page1}>169<br />170<h2>{question1.question}</h2>171<div className="container">172<div className="divid1">173<br />174<input type="text" className="input" name="" placeholder="Fullname" onChange={(event)=>setResponse1(event.target.value)}/>175<br />176<br />177</div>178</div>179</div>180<div id="surv" className={page2} hidden>181<br />182<h2>{question2.question}</h2>183<div className="radio_option">184<input type="radio" value="22" onClick={(event)=>setResponse2(question2.a)} name="r" className="radio"/>185<label className="font1">{question2.a}</label>186<br /><br />187<input type="radio" value="22" name="r" className="radio" onClick={(event)=>setResponse2(question2.b)}/>188<label className="font1">{question2.b}</label>189<br /><br />190<input type="radio" value="ww" name="r" className="radio" onClick={(event)=>setResponse2(question2.c)}/>191<label className="font1 magin1">{question2.c}</label>192<br /><br />193</div>194</div>195<div id="surv" className={page3} hidden>196<br />197<h2>{question3.question}</h2>198<div className="radio_option">199<input type="checkbox" name="e" className="checkbox" onClick={(event)=>updateBox('1', question3.a)}/>200<label className="font1">{question3.a}</label>201<br />202<br />203<input type="checkbox" onClick={(event)=>updateBox('2', question3.b)} value="22" name="e" className="checkbox"/>204<label className="font1">{question3.b}</label>205<br />206<br />207<input type="checkbox" onClick={(event)=>updateBox('3', question3.c)} value="." name="r" className="checkbox"/>208<label className="font1">{question3.c}</label>209<br />210<br />211</div>212</div>213<div id="surv" className={page4}>214<br />215<h2>Survey completed</h2>216<div className="container">217<b> start another survey now</b>218</div>219</div>220<button className="btn" onClick={()=>next()}>{button}</button>221</div>222</div>223);224 225}226exportdefaultApp;

If you followed all the steps from the beginning, you should have your survey application running now.

creating a survey application using strapi internationalization plugin

How Does the Code Work?

Let’s explain how the code above works to get a better understanding of the application.

1constgetsurvey=async(value)=>{2 3letTasks=await axios.get('http://localhost:1337/api/surveys?locale='+ value);4setQuestion1(Tasks.data.data\[0\]["attributes"]);5setQuestion2(Tasks.data.data\[QuestionNum1\]["attributes"]);6setQuestion3(Tasks.data.data\[QuestionNum2\]["attributes"]);7setQuestionNum1(prev=>QuestionNum1+2);8setQuestionNum2(prev=>QuestionNum2+2);9}

From the above code, what the getsurvey() method does is that it uses Axios to make requests to the backend. The internationalization language to get from the Strapi backend is specified by the variable value parameter.

When the user clicks on the Start Survey button, then the survey questions are loaded from strapi based on the language selected by the user. If the language selected by the user is French, then the survey questions will be in French by making use of strapi internationalization plugin.

1constaddTask=async(quest, valu)=>{2let res =await axios 3.post("http://localhost:1337/api/responses/",{4 5"data":{"Email": email,"surveyQuestion": quest,"surveyResponse": valu}6})7 8.catch((err)=>console.log(err));9 10};

We use the addTask() method to store the user responses to the backend. Whenever the user is through with a set of survey questions, and when the user clicks on the submit button, addTask() will be triggered to send the responses to the backend.

1useEffect(()=>{2setResponse3(prev=> checkbox.box1+","+ checkbox.box2+","+ checkbox.box3);3},[checkbox])

We use the useEffect hook to update the values for multiple option questions. Whenever the box is checked or unchecked, we then update it with the corresponding value.

Conclusion

Congratulations! You have successfully created a survey application from scratch.

In this tutorial, you learned how to set up Strapi for a survey application using the React.js library for the front end. We also learned how to use internationalization in Strapi to offer content in different languages.

You can view the code for this article here.

tweet selectionozb0xyjgtbkaksq2ddyb.jpgPopoola Temitopesoftware engineer and technical writer

Tag » How To Create A Simple Survey App React