How to Build Lightning Fast Surveys with Next.js and SurveyJS — SitePoint

On this text, we’ll stroll by the use of assemble a website that you need to make the most of to create new surveys, share your surveys, after which analyze the outcomes. Your website is perhaps lightning fast and is perhaps web site positioning nice, relying on all the latest choices in Subsequent.js. It may even be versatile and easy to assemble due to SurveyJSwhich makes working with surveys simple.

This article will assume you understand the basics of React and Subsequent.js, nonetheless it will stroll you through assemble every ingredient and net web page of the website. You’ll observe along with the article for the entire code, or you might leap to the highest and use the occasion repository proper right here. You might also take a look at the last word mannequin of the website that I’ve deployed for you proper right here.

Subsequent.js is a React-based framework that helps you assemble full-stack internet sites utterly in React. Subsequent.js handles the entire bundling and gives you extremely efficient APIs to resolve render each net web page so that it could be lightning fast. On this text, we’ll make sure that all our pages is perhaps rendered at assemble time. Due to this we’re capable of merely expose a sitemap that Google can use to index your website, which is necessary for making certain your web site positioning effectivity is good.

SurveyJS is an open-source sort administration software program that provides you the flexibleness to create, share and analyze your surveys and kinds. They provide a React API that we’ll use to create a survey administration system with Subsequent.js.

Setting Up Subsequent.js

First, let’s setup our Subsequent.js utility. It’s quick and easy to get started with Subsequent.js, as they provide a CLI software program that means that you can create a major app based totally on the preferences you give.

To utilize the software program it is worthwhile to make sure you have npx put in after which run the following command:

npx create-next-app@latest

While you run the create-next-app command it will ask you a set of questions regarding the mission that you must create. Most of the questions are utterly based totally on non-public alternative, so you might reply them nonetheless you need. For this textual content, we’ll be using pure JavaScript (fairly than Typescript) and we’ll even be using the model new app router in Subsequent.js fairly than the outdated file router.

Now that you have your Subsequent.js app prepare, you might run it with:

yarn run dev

This may occasionally depart you with a dev server working that may substitute any time you make modifications to your data. For now, let’s protect this working so we’re in a position so as to add pages with out having to rebuild every time.

Setting Up SurveyJS

To rearrange SurveyJS, we’re going to must put in the entire utterly completely different dependencies. We’re going to utilize the entire utterly completely different components of SurveyJS along with the form creator, the form present and the outcomes bundle, so we need to guarantee to place in all of them.

To place within the packages, make sure that to run the following arrange command:

yarn add survey-analytics survey-core survey-creator-core survey-creator-react survey-react-ui

Setting Up the Sort Creator

First, let’s start of by together with the form creator net web page. I’m going to make mine accessible at /creatorso to do that I create a file at /creator/net web page.js.

The creator doesn’t need any server-side data to render, so that implies that our net web page ingredient could also be very simple; it merely renders our Creator ingredient, which I will outline later. It looks like this:

export const metadata = {
  title: "Survey Creator",
};

export default function Net web page() {
  return Creator />;
}

Throughout the code above, you might even see that I export every the net web page and a metadata object. The metadata object will then be used for the web site positioning meta tags by Subsequent.js. For this net web page, we on a regular basis want to make use of the similar string, so we merely export an object.

The Creator ingredient is the place we actually use the SurveyJS API. Let’s take a look at the ingredient:

"use shopper";

import { useEffect, useState } from "react";
import { SurveyCreatorComponent, SurveyCreator } from "survey-creator-react";

export default function Creator() {
  let [creator, setCreator] = useState();

  useEffect(() => {
    const newCreator = new SurveyCreator({
      showLogicTab: true,
      showTranslationTab: true,
    });
    setCreator(newCreator);
  }, []);

  return div>{creator && SurveyCreatorComponent creator={creator} />}/div>;
}

The very very first thing you’ll uncover is we use the use shopper directive on this ingredient. It’s as a result of the SurveyJS components aren’t designed to be run as server components. To not worry, though; they’ll nonetheless be rendered on the server first sooner than being despatched to the patron.

The next issue you’ll see is that we run a useEffect with an empty dependency array. Due to this the function will run as quickly as and create the SurveyCreator. You’ll see at the moment we’re capable of transfer in any selections into the creator counting on what choices we have to enable.

All we now have to do is render the SurveyCreatorComponent and transfer it the creator object. We optionally render it so that it doesn’t break sooner than the creator is about up.

Your dev server must have been reloading as you go, so within the occasion you now go to /creatoryou’ll be succesful to entry the creator and use the entire choices like you might even see inside the screenshot beneath.

How to Build Lightning Fast Surveys with Next.js and SurveyJS — SitePoint

Create a Net web page to View the Sort

Subsequent we have to create an internet web page to view the categories that we’ve constructed. While you’ve created the form inside the designer, the output is perhaps a JSON object that may comprise your questions and the preferences you setup as you assemble the survey, along with any logic or varieties.

For our sort net web page, we have to use a dynamic setup so that we’re capable of render any number of sort pages with out having to create a model new file for every new sort. We try this by using Subsequent.js dynamic routes. To create a dynamic route, we now have to create a model new file at /app/sort/[slug]/net web page.js which can provide all our varieties a separate net web page at /sort/form-slug.

In our new file, we now have now to create quite a few capabilities to assist Subsequent.js to create our pages. First, let’s start with generateStaticParamswhich we’re in a position to make use of to tell Subsequent.js which pages we have to generate. Beneath you might even see the contents of the function:

export async function generateStaticParams() {
  return surveys.map((x) => ({ slug: x.slug }));
}

For this mission, we prepare a file that exports a list of surveys (which comprise a slug) and a survey (which is the merchandise equipped by the survey designer). If we have to add a model new survey, we merely need in order so as to add one different entry to our surveys array. Our generateStaticParams function should export a list of slugswhich Subsequent.js will then use to render our pages at assemble time. For us, that may be very simple; we merely should map our survey array to go well with the format:

export async function generateMetadata({ params }) {
  const survey = surveys.uncover((x) => x.slug === params.slug);

  return {
    title: survey.survey.title,
    description: survey.survey.description,
  };
}

The next function we’re going to try is generateMetadata. This takes inside the parameters from the static params function we merely outlined, after which it returns our title and description, which are used for the metadata on our internet net web page. As you might even see above, our function finds the right survey object based totally on the slug we’re given. Then we’re in a position to make use of the similar title and description that we wrote after we created our survey.

The very final thing we now have to stipulate in our net web page.js file is the React net web page itself. The online web page ingredient for our sort net web page could be fairly easy. It finds the survey object as soon as extra, then passes it by the use of to the SurveyComponent:

export default function Net web page({ params: { slug } }) {
  const survey = surveys.uncover((x) => x.slug === slug);

  return (
    div>
      SurveyComponent surveyData={survey.survey} />
    /div>
  );
}

The SurveyComponent then must be outlined individually. Try the ingredient:

"use shopper";

import { useCallback } from "react";
import { Model } from "survey-core";
import { Survey } from "survey-react-ui";

export default function SurveyComponent({ surveyData }) {
  const model = new Model(surveyData);

  const alertResults = useCallback(async (sender) => {
    fetch("/api/submit", {
      method: "POST",
      headers: {
        "Content material material-Type": "utility/json;charset=UTF-8",
      },
      physique: JSON.stringify({ finish consequence: sender.data }),
    });
  }, []);

  model.onComplete.add(alertResults);

  return Survey model={model} />;
}

As soon as extra, you’ll uncover that we now have now the use shopper directive to make sure Subsequent.js is conscious of it’s not a server ingredient. We then create a model with SurveyJS and transfer it into the SurveyJS Survey ingredient. Sooner than we do this, you’ll uncover that we prepare an onComplete function. In our case, the function merely sends the raw data to /api/submitwhich could then be handled there.

You must use Subsequent.js to create API endpoints. In our case, we’re capable of do it by making a file at /api/submit/route.js and putting a POST function in it, like so:

export async function POST(request) {
  const res = await request.json();

  console.log(res);

  return Response.json({ message: "Achieved" });
}

In our case, the POST function could also be very simple: it grabs the merchandise that’s despatched after which logs it to the console and responds with a message. That’s the place you will want to save lots of the top consequence to your database if in case you could have one. You might also choose to validate the top consequence further and return a finish consequence to point out on the frontend. At this degree, it’s utterly as a lot as you what you do with the data.

Making a Net web page to View the Outcomes

Now that we now have now prepare a way to create and present varieties, we now have to rearrange a way to try the outcomes we’ve collected from our varieties. Clearly, a way to try the outcomes is just to look straight on the database, nonetheless that gained’t give you any insights into traits which could be exhibiting in your surveys. If we have to set up traits, we’re in a position to make use of the surveyjs-analytics bundle.

For this mission, I’ve created some fake finish consequence data so we’re capable of create a outcomes dashboard. I’ve added a outcomes array to each survey object that we used earlier. Each finish consequence appears one factor like this:

  {
    "nps-score": 9,
    "disappointing-experience": [
      "The service is great, i highly recommend you use it.",
    ],
    "improvements-required": [
      "The service is great, i highly recommend you use it.",
    ],
    "promoter-features": ["ui"],
    rebuy: [true, false],
  }

As you might even see, each consequence’s merely an object that has the question ID as a key and the reply as a price. That’s exactly what we get from the onComplete function when the form is submitted.

First, we have to create a model new dynamic net web page, as we’ll must create a model new internet net web page for each utterly completely different sort so we’re capable of current the outcomes for that sort notably. For this net web page, we have to create a model new file at /outcomes/[slug]/net web page.js.

As soon as extra, we have to define a generateMetadata and a generateStaticParams like we did to point out the categories. In our generateMetadata function, we make a slight tweak to the title so it’s clear that we’re wanting on the outcomes fairly than the form itself. The one distinction this time is that, inside our generateStaticParamswe filter a number of of the categories that don’t have outcomes so we don’t generate an internet web page for varieties with none outcomes. Our generateStaticParams function ends up wanting like this:

export async function generateStaticParams() {
  return surveys
    .filter((x) => x.outcomes.dimension > 0)
    .map((x) => ({ slug: x.slug }));
}

As soon as extra, we have to moreover export a Net web page ingredient. Our net web page ingredient is equal to the net web page ingredient from the sooner half, apart from as an alternative we render the ingredient Outcomes. Nevertheless we nonetheless do a uncover to grab the exact survey data and transfer that by the use of to the ingredient.

Our Outcomes ingredient tons of in your complete required packages after which renders them to the net web page. It requires quite a few useEffect hooks to rearrange, and your complete ingredient looks like this:

"use shopper";

import { useEffect } from "react";
import { Model } from "survey-core";

export default function Outcomes({ surveyData }) {
  useEffect(() => {
    (async () => {
      const survey = new Model(surveyData.survey);

      const { VisualizationPanel } = await import("survey-analytics");

      const currentPanel = new VisualizationPanel(
        survey.getAllQuestions(),
        surveyData.outcomes,
        {
          allowHideQuestions: false,
        }
      );

      currentPanel.render("surveyVizPanel");

      return () => {
        const panelElement = doc.getElementById("surveyVizPanel");

        if (panelElement) {
          panelElement.innerHTML = "";
        }
      };
    })();
  }, [surveyData]);

  return (
    div>
      div id="surveyVizPanel" />
    /div>
  );
}

As you might even see, we as soon as extra start with the use shopper directive for all of the similar causes as sooner than. The ingredient begins with a useEffect that’s used to rearrange the panel that reveals the entire charts. It firstly makes use of the surveyData object, which defines the survey itself to create a Model. This lets the outcomes bundle know which graphs to point, as it should in all probability understand each question.

The next issue the useEffect does is load the survey-analytics bundle. We try this by the use of a dynamic import, so it isn’t loaded at assemble time. This technique prevents build-time errors attributable to client-side specific code inside the bundle.

After getting the required bundle, we prepare the visualization object with your complete questions after which we are able to present it a list of the entire submissions for it to endure and create graphs from. At this degree you might configure your visualizations with the alternatives equipped. After that, all you have to do is let the panel object know which ID to utilize to render to inside the DOM, which in our case is surveyVizPanelwhich we render further down. Lastly, we now have now to make sure to supply a clean-up function to our hook so that it clears out the part when it’s completed.

You’ll uncover that we solely transfer inside the surveyData to the dependency array so that we solely re-render the entire graphs if the enter data modifications, which is more likely to be the case if we ever hyperlink between utterly completely different outcomes pages.

Extra Work

This textual content has given you enough of an thought to get started integrating SurveyJS into your Subsequent.js utility. To have a very functioning system, you’ll must look into together with some type of authentication system with the intention to make sure that solely verified prospects can entry the utterly completely different components of the system.

You’ll moreover want to mix with some type of data provide, every for the creator to create new varieties and to collect the outcomes from the highest particular person. All of these additions are made quite simple in Subsequent.js and SurveyJS.

Conclusion

This data has confirmed you assemble a whole survey administration system in Subsequent.js with SurveyJS. You get so many benefits out of the sphere with Subsequent.js, so although you will not have written that loads code, you’ll uncover that what you have gotten created will scale to as many sorts as you want with none downside.

Thanks for taking the time to be taught this data. As I beforehand talked about, you might check out the overall repo proper right here or you might play with the hosted mannequin of the system proper right here.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *