Skip to main content

Sitecore

Integrate Sitecore Form into a JSS app (React/Next.js) in Headless Architecture.

Headless Man

Everyone is moving toward headless architecture these days and wants to take advantage of the new approach in the CMS industry to improve the CMS experience. However, in a few cases, it does not support a CMS functionality like Sitecore Form. Sitecore does not have any out of the box (OOB) component to implement Sitecore Form. Although Sitecore has provided different approaches and advice on how to integrate Sitecore Form in JSS app.

I have gone through multiple Sitecore documents and consolidated all the details in following steps. So, you will be able to implement forms powered by the Sitecore Forms API in React and Next.js in a headless architecture.

  • Create the form in Sitecore.
  • Create a form rendering for the JSS app.
  • Add the form rendering to the page/app route.
  • Install SDK and create the form component in your JSS application.
  • Switch the pre-rendering method SSG to SSR.

You must configure your JSS app before utilizing Sitecore Form. You can fetch data from the Sitecore Layout Service using REST or GraphQL, but to deal with Sitecore Forms, you must set FETCH_WITH=REST in the .env file in the JSS app.

1. Create the Form in Sitecore.

Here we are creating simple Sitecore Form. If you are familiar with it, you can skip this step.

  1. Go to the Sitecore Dashboard and select Forms, then click Create.

Fig 1 - Select Forms On Sitecore Dashboard 1: Select Forms on Sitecore Dashboard.

Fig 2 Create Form2: Create Form

  1. Add the form elements from the Form Elements pane.
  2. Add a Submit button to your form from the Structure section and drag the Submit button element onto the form canvas.
  3. To store the Form data on click of save button, set the submit actions to Save Data .

Fig 3 Drag And Drop Form Elements And Submit Button From Structure Section3: Drag and drop form elements and Submit button from the Structure section.

2. Create a Form Rendering for the JSS App.

To add a Sitecore form to the JSS app, you must have a JSS Component to render the form. A form component is a normal JSS component.

  1. Create the Component definitions (Rendering and Placeholder settings) in Sitecore using the JSS CLI:
jss deploy component Form --allowedPlaceholders jss-main
  1. We can change the allowed Placeholder to the placeholder name you want to allow the form to be added to.
  2. In the Sitecore Content Editor, navigate to the Rendering item that was created (/Sitecore/layout/Renderings/Project/$yourappname/Form)
  3. Set the Datasource location field to /sitecore/forms.
  4. Set the Datasource template field to /sitecore/templates/System/Forms/Form.
  5. Set the Rendering Contents Resolver field to Sitecore Forms Resolver. This causes JSS to deliver form data to the component instead of item data.

Fig 4 Set The Fields Of Form Rendering Created By Cli Command For Jss App4: Set the fields of Form Rendering created by CLI command for JSS app.

3. Add the Form Rendering to Page/App Route.

  1. In the Experience Editor, navigate to the JSS route item you want to add the form to.
  2. Select the new Form component rendering into the placeholder it is allowed in.

Fig 5 Adding Form Rendering In Main(main Jss) Placeholder5: Adding Form Rendering in the Main(main-jss) placeholder.

  1. Select the Sitecore Form you created previously as the Associated Content.

Fig 6 Select The Form You Created In Sitecore     6: Select the Form you created in Sitecore.

Fig 7 Added Form Rendering To Page Or App Rout     7: Added Form Rendering to Page/app rout.

4. Install SDK and Create the Form Component in Your JSS Application.

Install the Sitecore JavaScript Rendering SDK Forms for React package, along with its dependencies, in a JSS React or Next.js application.

  1. Go to the root directory of your JSS React or Next.js application, and run the following npm command:
npm install @sitecore-jss/sitecore-jss-forms @sitecore-jss/sitecore-jss-react-forms
  1. Create JSS Component named as Form in your JSS application using:
jss scaffold Form
  1. In src/components/Form.tsx implement the form a component as below.
import { Form } from '@sitecore-jss/sitecore-jss-react-forms';
import React from 'react';
import { withRouter } from 'next/router';
import { sitecoreApiHost, sitecoreApiKey } from '../temp/config';

const JssNextForm = ({ fields, router }: any) => (
    <Form
      form={fields}
      sitecoreApiHost={''}
      sitecoreApiKey={sitecoreApiKey}
      onRedirect={(url) => router.push(url)}
    />
  );

export default withRouter(JssNextForm);

Note: You must set sitecoreApiHost to an empty string, for example, sitecoreApiHost={”}, to send requests to the Next.js server. And Sitecore form Rendering name and JSS form component File name must match.

5. Switch the Pre-Rendering Method SSG to SSR.

To switch the JSS Next.js application from SSG to SSR:

  1. Move/rename/delete src/pages/[[..path]].tsx.
  2. Download the file from [[..path]].SSR.tsxto src/pages/ and rename it to [[..path]].tsx.
  3. Or create a new file in src/pages/named as [[..path]].tsx and add below SSR code:
import { useEffect } from 'react';
import { GetServerSideProps } from 'next';
import NotFound from 'src/NotFound';
import Layout from 'src/Layout';
import { SitecorePageProps } from 'lib/page-props';
import { sitecorePagePropsFactory } from 'lib/page-props-factory';
import { componentFactory } from 'temp/componentFactory';
import {
  SitecoreContext,
  ComponentPropsContext,
  handleEditorFastRefresh,
} from '@sitecore-jss/sitecore-jss-nextjs';

const SitecorePage = ({
  notFound,
  componentProps,
  layoutData
}: SitecorePageProps): JSX.Element => {
  useEffect(() => {
    // Since Sitecore editors do not support Fast Refresh, need to refresh EE chromes after Fast Refresh finished
    handleEditorFastRefresh();
  }, []);

  if (notFound) {
    // Shouldn't hit this (as long as 'notFound' is being returned below), but just to be safe
    return <NotFound />;
  }

  return (
    <ComponentPropsContext value={componentProps}>
      <SitecoreContext
        componentFactory={componentFactory}
        layoutData = {layoutData}>
        <Layout layoutData={layoutData} />
      </SitecoreContext>
    </ComponentPropsContext>
  );
};

// This function gets called at request time on server-side.
export const getServerSideProps: GetServerSideProps = async (context) => {
  const props = await sitecorePagePropsFactory.create(context);

  return {
    props,
    notFound: props.notFound, // Returns custom 404 page with a status code of 404 when true
  };
};
export default SitecorePage;

Fig 8 Jss App Form Component And Ssr Re Rendering Files8: Form Component and SSR re-rendering files created in the JSS app.

  1. Optionally, delete /src/lib/sitemap-fetcher.ts.
  2. Run the JSS app in connected mode by command:
jss start:connected
  1. Results:

Fig 9 Jss App Form Submission View9: JSS app form submission page view.

 

Fig 10 Sitecore Experience Editor Form Submission Page View 10: Sitecore Experience Editor form submission page view.

 

Fig 11 Form Submission Data 11: Form submission data.

Note: There are several restrictions when integrating Sitecore Form with the JSS app, as noted down below.

  • JSS app must run in Connected mode to Sitecore.
  • JSS Forms does not support Sitecore Robot detection.
  • Accept form submissions and return JSON data in a REST.

Sitecore may add these features in Headless architecture in future releases.

Happy learning…

Thoughts on “Integrate Sitecore Form into a JSS app (React/Next.js) in Headless Architecture.”

  1. Thank you for the detailed guide to setup Sitecore Forms with NextJS. It surely helped me resolve many issues with the implementation.

    However, currently the site is in SSG mode for Static generation of pages.
    So, if I change the root [[…path]].tsx to the SSR it works correctly, but if I try to keep the root paths file SSG and add a custom route for a subpage, for example: src/pages/forms/[[…path]].tsx in SSR, I am getting a 404 error.

    Could you please let me know any examples on how to achieve this?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Avinash

Avinash is a Senior Technical Consultant at Perficient. He has technical experience in Microsoft technologies such as Azure, ASP.Net MVC, ASP.Net, Web API, and MSSQL. Additionally, He is developing expertise in CMS platforms like Sitecore, Sitecore SXA, Sitecore Headless and Optimizely.

More from this Author

Follow Us
TwitterLinkedinFacebookYoutubeInstagram