React Form Builder
SurveyJS Form Builder is an open-source UI component in React that seamlessly integrates with any backend system and allows you to create and style multiple dynamic HTML forms right in your React application. This component generates form definitions (schemas) in real-time and offers a no-code drag-and-drop interface that makes form creation accessible to anyone. The form builder features a dedicated GUI for conditional rules and form branching and an integrated CSS theme editor for custom form styling and branding. This step-by-step tutorial will help you get started with the Form Builder component in a React application. To add the component to your application, follow the steps below:
- Install the
survey-creator-react
npm Package - Configure Styles
- Configure Survey Creator
- Render Survey Creator
- Save and Load Survey Model Schemas
- Manage Image Uploads
If you are looking for a quick-start application that includes all SurveyJS components, refer to the following GitHub repositories:
In this guide, the terms "Form Builder" and "Survey Creator" are used interchangeably and both refer to the SurveyJS form building component for React.
Install the React Form Builder npm Package
Survey Creator for React consists of two npm packages: survey-creator-core
(platform-independent code) and survey-creator-react
(rendering code). Run the following command to install survey-creator-react
. The survey-creator-core
package will be installed automatically as a dependency.
npm install survey-creator-react --save
Configure Styles
Create a React component that will render Survey Creator and import Survey Creator and SurveyJS Form Library style sheets as shown below:
// components/SurveyCreator.tsx
import "survey-core/survey-core.css";
import "survey-creator-core/survey-creator-core.css";
Survey Creator allows users to customize its interface at runtime using UI themes. Four themes are available out-of-the-box: Light, Dark, Contrast, and Survey Creator 2020. The configuration above applies the Light theme. If you want to apply a different predefined theme or create a custom theme, refer to the following help topic for detailed instructions:
Configure Survey Creator
To configure the Survey Creator component, specify its properties in a configuration object. In this tutorial, the object enables the following properties:
autoSaveEnabled
Automatically saves the survey JSON schema on every change.collapseOnDrag
Collapses pages on the design surface when users start dragging a survey element.
// components/SurveyCreator.tsx
import { ICreatorOptions } from "survey-creator-core";
const defaultCreatorOptions: ICreatorOptions = {
autoSaveEnabled: true,
collapseOnDrag: true
};
Pass the configuration object to the SurveyCreator
constructor as shown in the code below to instantiate Survey Creator. Assign the produced instance to a constant that will be used later to render the component:
// components/SurveyCreator.tsx
// ...
import { useState } from "react";
import { SurveyCreator } from "survey-creator-react";
const defaultCreatorOptions: ICreatorOptions = { /* ... */ }
export default function SurveyCreatorWidget(props: { json?: Object, options?: ICreatorOptions }) {
let [creator, setCreator] = useState<SurveyCreator>();
if (!creator) {
creator = new SurveyCreator(props.options || defaultCreatorOptions);
setCreator(creator);
}
return "...";
}
View Full Code
// components/SurveyCreator.tsx
import { useState } from "react";
import { ICreatorOptions } from "survey-creator-core";
import { SurveyCreator } from "survey-creator-react";
import "survey-core/survey-core.css";
import "survey-creator-core/survey-creator-core.css";
const defaultCreatorOptions: ICreatorOptions = {
autoSaveEnabled: true,
collapseOnDrag: true
};
export default function SurveyCreatorWidget(props: { json?: Object, options?: ICreatorOptions }) {
let [creator, setCreator] = useState<SurveyCreator>();
if (!creator) {
creator = new SurveyCreator(props.options || defaultCreatorOptions);
setCreator(creator);
}
return "...";
}
Render Survey Creator
To render Survey Creator, import the SurveyCreatorComponent
, add it to the template, and pass the instance you created in the previous step to the component's creator
attribute, as shown below.
SurveyJS components do not support server-side rendering (SSR). If you are using Next.js or another framework that has adopted React Server Components, you need to explicitly mark the React component that renders a SurveyJS component as client code using the 'use client' directive.
// components/SurveyCreator.tsx
'use client'
// ...
import { SurveyCreatorComponent } from "survey-creator-react";
const defaultCreatorOptions: ICreatorOptions = { /* ... */ }
export function SurveyCreatorWidget() {
let [creator, setCreator] = useState<SurveyCreator>();
if (!creator) {
creator = new SurveyCreator(props.options || defaultCreatorOptions);
setCreator(creator);
}
return (
<div style={{ height: "100vh", width: "100%" }}>
<SurveyCreatorComponent creator={creator} />
</div>
);
}
The lack of SSR support may cause hydration errors if a SurveyJS component is pre-rendered on the server. To ensure against those errors, use dynamic imports with ssr: false
for React components that render SurveyJS components. The following code shows how to do this in Next.js:
// creator/page.tsx
import dynamic from 'next/dynamic';
const SurveyCreatorComponent = dynamic(() => import("@/components/SurveyCreator"), {
ssr: false
});
export default function SurveyCreator() {
return (
<SurveyCreatorComponent />
);
}
View Full Code
// components/SurveyCreator.tsx
'use client'
import { useState } from "react";
import { ICreatorOptions } from "survey-creator-core";
import { SurveyCreator, SurveyCreatorComponent } from "survey-creator-react";
import "survey-core/survey-core.css";
import "survey-creator-core/survey-creator-core.css";
const defaultCreatorOptions: ICreatorOptions = {
autoSaveEnabled: true,
collapseOnDrag: true
};
export default function SurveyCreatorWidget(props: { json?: Object, options?: ICreatorOptions }) {
let [creator, setCreator] = useState<SurveyCreator>();
if (!creator) {
creator = new SurveyCreator(props.options || defaultCreatorOptions);
setCreator(creator);
}
return (
<div style={{ height: "100vh", width: "100%" }}>
<SurveyCreatorComponent creator={creator} />
</div>
);
}
// creator/page.tsx
import dynamic from 'next/dynamic';
const SurveyCreatorComponent = dynamic(() => import("@/components/SurveyCreator"), {
ssr: false
});
export default function SurveyCreator() {
return (
<SurveyCreatorComponent />
);
}
Save and Load Survey Model Schemas
Survey Creator produces survey model schemas as JSON objects. You can persist these objects on your server: save updates and restore previously saved schemas. To save a JSON object, implement the saveSurveyFunc
function. It accepts two arguments:
saveNo
An incremental number of the current change. Since web services are asynchronous, you cannot guarantee that the service receives the changes in the same order as the client sends them. For example, change #11 may arrive to the server faster than change #10. In your web service code, update the storage only if you receive changes with a highersaveNo
.callback
A callback function. Call it and passsaveNo
as the first argument. Set the second argument totrue
orfalse
based on whether the server applied or rejected the change.
The following code shows how to use the saveSurveyFunc
function to save a survey model schema in the browser's localStorage
or in your web service:
// components/SurveyCreator.tsx
// ...
export default function SurveyCreatorWidget(props: { json?: Object, options?: ICreatorOptions }) {
// ...
creator.saveSurveyFunc = (saveNo: number, callback: (num: number, status: boolean) => void) => {
// If you use localStorage:
window.localStorage.setItem("survey-json", creator.text);
callback(saveNo, true);
// If you use a web service:
saveSurveyJson(
"https://your-web-service.com/",
creator.JSON,
saveNo,
callback
);
};
// ...
}
// If you use a web service:
function saveSurveyJson (url: string, json: object, saveNo: number, callback: (num: number, status: boolean) => void) {
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify(json)
})
.then(response => {
if (response.ok) {
callback(saveNo, true);
} else {
callback(saveNo, false);
}
})
.catch(error => {
callback(saveNo, false);
});
}
If you are running a NodeJS server, you can check a survey JSON schema before saving it. On the server, create a SurveyModel
and call its toJSON()
method. This method deletes unknown properties and incorrect property values from the survey JSON schema:
// Server-side code for a NodeJS backend
import { Model } from "survey-core";
const incorrectSurveyJson = { ... };
const survey = new Model(surveyJson);
const correctSurveyJson = survey.toJSON();
// ...
// Save `correctSurveyJson` in a database
// ...
To load a survey model schema into Survey Creator, assign the schema to Survey Creator's JSON
or text
property. Use text
if the JSON object is converted to a string; otherwise, use JSON
. The following code takes a survey model schema from component props or the localStorage
. If the schema is not found (for example, when Survey Creator is launched for the first time), a default JSON is used:
// components/SurveyCreator.tsx
// ...
const defaultJson = {
pages: [{
name: "Name",
elements: [{
name: "FirstName",
title: "Enter your first name:",
type: "text"
}, {
name: "LastName",
title: "Enter your last name:",
type: "text"
}]
}]
};
export default function SurveyCreatorWidget(props: { json?: Object, options?: ICreatorOptions }) {
// ...
creator.text = JSON.stringify(props.json) || window.localStorage.getItem("survey-json") || JSON.stringify(defaultJson);
// ...
}
View Full Code
// components/SurveyCreator.tsx
'use client'
import { useState } from "react";
import { ICreatorOptions } from "survey-creator-core";
import { SurveyCreatorComponent, SurveyCreator } from "survey-creator-react";
import "survey-core/survey-core.css";
import "survey-creator-core/survey-creator-core.css";
const defaultCreatorOptions: ICreatorOptions = {
autoSaveEnabled: true
};
const defaultJson = {
pages: [{
name: "Name",
elements: [{
name: "FirstName",
title: "Enter your first name:",
type: "text"
}, {
name: "LastName",
title: "Enter your last name:",
type: "text"
}]
}]
};
export default function SurveyCreatorWidget(props: { json?: Object, options?: ICreatorOptions }) {
let [creator, setCreator] = useState<SurveyCreator>();
if (!creator) {
creator = new SurveyCreator(props.options || defaultCreatorOptions);
setCreator(creator);
}
creator.saveSurveyFunc = (saveNo: number, callback: (num: number, status: boolean) => void) => {
window.localStorage.setItem("survey-json", creator.text);
callback(saveNo, true);
// saveSurveyJson(
// "https://your-web-service.com/",
// creator.JSON,
// saveNo,
// callback
// );
};
creator.text = JSON.stringify(props.json) || window.localStorage.getItem("survey-json") || JSON.stringify(defaultJson);
return (
<div style={{ height: "100vh", width: "100%" }}>
<SurveyCreatorComponent creator={creator} />
</div>
);
}
// function saveSurveyJson (url: string, json: object, saveNo: number, callback: (num: number, status: boolean) => void) {
// fetch(url, {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json;charset=UTF-8'
// },
// body: JSON.stringify(json)
// })
// .then(response => {
// if (response.ok) {
// callback(saveNo, true);
// } else {
// callback(saveNo, false);
// }
// })
// .catch(error => {
// callback(saveNo, false);
// });
// }
// creator/page.tsx
import dynamic from 'next/dynamic';
const SurveyCreatorComponent = dynamic(() => import("@/components/SurveyCreator"), {
ssr: false
});
export default function SurveyCreator() {
return (
<SurveyCreatorComponent />
);
}
Manage Image Uploads
When survey authors design a form or questionnaire, they can add images to use as a survey logo or background, in the survey header, or within Image and Image Picker questions. Those images are embedded in the survey and theme JSON schemas as Base64 URLs. However, this technique increases the schema size. To avoid this, you can upload images to a server and save only image links in the JSON schemas.
To implement image upload, handle the onUploadFile
event. Its options.files
parameter stores the images you should send to your server. Once the server responds with an image link, call the options.callback(status, imageLink)
method. Pass "success"
as the status
parameter and a link to the uploaded image as the imageLink
parameter.
// components/SurveyCreator.tsx
// ...
import { SurveyCreatorModel, UploadFileEvent } from "survey-creator-core";
export default function SurveyCreatorWidget(props: { json?: Object, options?: ICreatorOptions }) {
// ...
creator.onUploadFile.add((_: SurveyCreatorModel, options: UploadFileEvent) => {
const formData = new FormData();
options.files.forEach((file: File) => {
formData.append(file.name, file);
});
fetch("https://example.com/uploadFiles", {
method: "post",
body: formData
}).then(response => response.json())
.then(result => {
options.callback(
"success",
// A link to the uploaded file
"https://example.com/files?name=" + result[options.files[0].name]
);
})
.catch(error => {
options.callback('error');
});
});
// ...
}
To view the application, run npm run dev
in a command line and open http://localhost:3000/ in your browser.
View Full Code
// components/SurveyCreator.tsx
// ...
'use client'
import { useState } from "react";
import {
ICreatorOptions,
// SurveyCreatorModel,
// UploadFileEvent
} from "survey-creator-core";
import { SurveyCreatorComponent, SurveyCreator } from "survey-creator-react";
import "survey-core/survey-core.css";
import "survey-creator-core/survey-creator-core.css";
const defaultCreatorOptions: ICreatorOptions = {
autoSaveEnabled: true
};
const defaultJson = {
pages: [{
name: "Name",
elements: [{
name: "FirstName",
title: "Enter your first name:",
type: "text"
}, {
name: "LastName",
title: "Enter your last name:",
type: "text"
}]
}]
};
export default function SurveyCreatorWidget(props: { json?: Object, options?: ICreatorOptions }) {
let [creator, setCreator] = useState<SurveyCreator>();
if (!creator) {
creator = new SurveyCreator(props.options || defaultCreatorOptions);
setCreator(creator);
}
creator.saveSurveyFunc = (saveNo: number, callback: (num: number, status: boolean) => void) => {
window.localStorage.setItem("survey-json", creator.text);
callback(saveNo, true);
// saveSurveyJson(
// "https://your-web-service.com/",
// creator.JSON,
// saveNo,
// callback
// );
};
// creator.onUploadFile.add((_: SurveyCreatorModel, options: UploadFileEvent) => {
// const formData = new FormData();
// options.files.forEach((file: File) => {
// formData.append(file.name, file);
// });
// fetch("https://example.com/uploadFiles", {
// method: "post",
// body: formData
// }).then(response => response.json())
// .then(result => {
// options.callback(
// "success",
// // A link to the uploaded file
// "https://example.com/files?name=" + result[options.files[0].name]
// );
// })
// .catch(error => {
// options.callback('error');
// });
// });
creator.text = JSON.stringify(props.json) || window.localStorage.getItem("survey-json") || JSON.stringify(defaultJson);
return (
<div style={{ height: "100vh", width: "100%" }}>
<SurveyCreatorComponent creator={creator} />
</div>
);
}
// function saveSurveyJson (url: string, json: object, saveNo: number, callback: (num: number, status: boolean) => void) {
// fetch(url, {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json;charset=UTF-8'
// },
// body: JSON.stringify(json)
// })
// .then(response => {
// if (response.ok) {
// callback(saveNo, true);
// } else {
// callback(saveNo, false);
// }
// })
// .catch(error => {
// callback(saveNo, false);
// });
// }
// creator/page.tsx
import dynamic from 'next/dynamic';
const SurveyCreatorComponent = dynamic(() => import("@/components/SurveyCreator"), {
ssr: false
});
export default function SurveyCreator() {
return (
<SurveyCreatorComponent />
);
}