Implement a Sitecore form in a JSS React app

Abstract

Implement a Sitecore form in a React JSS application

This topic describes how to implement an existing Sitecore form in a JSS React application.

Note

This topic assumes that you have the required JSS for React package installed, and that you already have created a Form rendering component with the appropriate JSS route, as depicted in this walkthrough.

To implement a Sitecore form in a React JSS application:

  1. To make the form render, you must tell the application how to render the Sitecore Forms schema. In the src/components/Form/index.js file, create a new component with the following content:

    import React from 'react';
    import { SitecoreForm } from '@sitecore-jss/sitecore-jss-forms';
    
    export default function Form(props) {
      /** @type {SitecoreForm} */
      const form = props.fields;
    
      // dump the form data out to the page
      return <code>{JSON.stringify(form, null, 2)}</code>;
    }
  2. To use the sample React forms implementation, modify your Form component to use the library's form components and withRouter from react-router-dom:

    import { Form } from '@sitecore-jss/sitecore-jss-react-forms';
    import React from 'react';
    import { withRouter } from 'react-router-dom';
    import { sitecoreApiHost, sitecoreApiKey } from '../../temp/config';
    
    const JssReactForm = ({ fields, history }) => (
      <Form
        form={fields}
        sitecoreApiHost={sitecoreApiHost}
        sitecoreApiKey={sitecoreApiKey}
        onRedirect={(url) => history.push(url)}
      />
    );
    
    export default withRouter(JssReactForm);
  3. Start the JSS app in connected mode:

    jss start:connected
  4. You can see the form data dumped to the page as JSON.

Note

In headless mode, if you send requests directly to the Sitecore instance, you get an error. You must set sitecoreApiHost to an empty string, for example sitecoreApiHost={''}, so that requests are sent directly to your node server.