---
title: Generate Domain Model Code
product: Survey Creator
description: With SurveyJS, you can collect data from your clients and users without having to build a client-side app with multiple pages for each form. View a free demo for JavaScript to learn how to generate form definition for a domain model in JSON and edit both of them in a no-code visual editor.
framework: React
source: https://surveyjs.io/survey-creator/examples/create-domain-models/reactjs
index: https://surveyjs.io/survey-creator/examples/overview.md
---

# Generate Domain Model Code (React)

This example demonstrates how to generate server-side domain model code based on a client-side survey JSON schema. This functionality is part of a wider use case described in the following help topic: [No-code Editor for Domain Models](https://surveyjs.io/documentation/no-code-editor-for-domain-models).

To generate domain model code in your application, implement a text parser that converts JSON to the server-side code language you prefer (C# in this demo). View the `codegenerator.js` file to see the implementation.

In this demo, you can see the generated domain model code under the Domain Model Code tab in Survey Creator. To implement this UI, create a component that renders a `<textarea>` and call the [`addTab(tabOptions)`](https://surveyjs.io/survey-creator/documentation/api-reference/survey-creator#addTab) method on a [`SurveyCreatorModel`](https://surveyjs.io/survey-creator/documentation/api-reference/survey-creator) instance to register the component as a plugin.

Domain model property names are converted from form field names, so you need to ensure against unsupported symbols. Handle Survey Creator's [`onPropertyDisplayCustomError`](https://surveyjs.io/survey-creator/documentation/api-reference/survey-creator#onPropertyDisplayCustomError) event to validate the names.

## Files

### `public/index.html`

```html
<!-- Uncomment the following lines to enable Ace Editor in the JSON Editor tab -->
<!-- 
<script src="https://unpkg.com/ace-builds/src-min-noconflict/ace.js"></script>
<script src="https://unpkg.com/ace-builds/src-min-noconflict/ext-searchbox.js"></script>
<script src="https://unpkg.com/ace-builds/src-min-noconflict/theme-clouds_midnight.js"></script>
-->

<div id="surveyCreatorContainer" style="position: absolute; height: 100%; width: 100%"></div>
```

### `src/codegenerator.js`

```js
function isNameCorrect(name) {
    return /^@?[a-zA-Z_]\w*(\.@?[a-zA-Z_]\w*)*$/.test(name);
}

function isListQuestionType(el) {
    return ["paneldynamic", "matrixdynamic", "matrixdropdown"].indexOf(el.getType()) > -1;
}

function getNestedItemClassName(name) {
    return name + "Item";
}

function getElementTypeName(el) {
    if (isListQuestionType(el)) return "IList<" + getNestedItemClassName(el.name) + ">";
    if (el.getType() === "text") {
        if (el.inputType === "number") return "int";
        if (el.inputType === "date" || el.inputType === "localedate") return "DateTime";
    }
    if (el.getType() === "boolean") return "bool"
    return "string";
}
function getCodePadding() { return "    "; }

function generateClassByElements(className, elements, lines) {
    lines.push("public class " + className + " {");
    elements.forEach(el => {
        if (el.isQuestion || el.getType() === "matrixdropdowncolumn") {
            lines.push(getCodePadding() + getElementTypeName(el) + " " + el.name + " { get; set; }")
        }
    });
    lines.push("}")
}

export function generateDomainModelCode(survey) {
    const lines = [];
    generateClassByElements(survey.name, survey.getAllQuestions(), lines);
    survey.getAllQuestions().forEach(q => {
        if (!isListQuestionType(q)) return;
        if (q.getType() === "paneldynamic") {
            lines.push("");
            generateClassByElements(getNestedItemClassName(q.name), q.elements, lines);
        } else {
            lines.push("");
            generateClassByElements(getNestedItemClassName(q.name), q.columns, lines);
        }
    });
    return lines.join("\n");
}
```

### `src/survey_json.js`

```js
export const formJSON = {
  "name": "PatientAssessment",
  "title": "Patient Assessment Form",
  "checkErrorsMode": "onValueChanged",
  "questionErrorLocation": "bottom",
  "pages": [
    {
      "name": "PatientInformation",
      "title": "Patient information",
      "navigationTitle": "Patient information",
      "elements": [
        {
          "type": "panel",
          "name": "patient-information",
          "title": "All fields with an asterisk (*) are required fields, and must be filled out in order to process the information in strict confidentiality.",
          "elements": [
            {
              "type": "text",
              "name": "FirstName",
              "title": "First name",
              "isRequired": true
            },
            {
              "type": "text",
              "name": "LastName",
              "startWithNewLine": false,
              "title": "Last name",
              "isRequired": true
            },
            {
              "type": "text",
              "name": "SSN",
              "title": "Social Security number",
              "requiredErrorText": "You SSN must be a 9-digit number.",
              "isRequired": true
            },
            {
              "type": "text",
              "name": "BirthDate",
              "startWithNewLine": false,
              "title": "Date of birth",
              "isRequired": true,
              "inputType": "date"
            },
            {
              "type": "text",
              "name": "Concerns",
              "title": "List any concerns you want to talk about during your visit"
            }
          ]
        }
      ]
    },
    {
      "name": "HealthHistory",
      "title": "Health history",
      "navigationTitle": "Health history",
      "elements": [
        {
          "type": "panel",
          "name": "health-history",
          "elements": [
            {
              "type": "boolean",
              "name": "Diabetes",
              "title": "Do you have diabetes?",
              "startWithNewLine": false
            },
            {
              "type": "boolean",
              "name": "HighBloodPressure",
              "title": "High blood pressure?",
              "startWithNewLine": false
            },
            {
              "type": "boolean",
              "name": "HighCholesterol",
              "title": "High cholesterol?",
              "startWithNewLine": false
            },
            {
              "type": "comment",
              "name": "OtherHealthConditions",
              "title": "Do you have other health conditions?"
            }
          ]
        }
      ]
    },
    {
      "name": "SocialHistory",
      "title": "Social history",
      "navigationTitle": "Social history",
      "elements": [
        {
          "type": "panel",
          "name": "social-history",
          "elements": [
            {
              "type": "panel",
              "name": "smoking",
              "elements": [
                {
                  "type": "radiogroup",
                  "name": "Cigarettes",
                  "title": "Do you smoke cigarettes?",
                  "choices": [
                    {
                      "value": "never",
                      "text": "Never"
                    },
                    {
                      "value": "yes",
                      "text": "Yes"
                    },
                    {
                      "value": "quit",
                      "text": "Quit"
                    }
                  ]
                },
                {
                  "type": "text",
                  "name": "CigarettesPacksPerDay",
                  "visibleIf": "{Cigarettes} = 'yes'",
                  "title": "How many packs a day?",
                  "inputType": "number",
                  "min": 0
                },
                {
                  "name": "date-quit",
                  "title": "CigarettesDateQuit",
                  "inputType": "date",
                  "maxValueExpression": "today()",
                  "visibleIf": "{Cigarettes} = 'quit'"
                },
                {
                  "name": "CigarettesYearsSmoked",
                  "title": "Years smoked",
                  "inputType": "number",
                  "min": 0,
                  "visibleIf": "{Cigarettes} = 'quit'"
                },
                {
                  "type": "boolean",
                  "name": "CigarettesVape",
                  "title": "Do you vape (e-cigarettes)?"
                }
              ]
            },
            {
              "type": "panel",
              "name": "alcohol-use-history",
              "elements": [
                {
                  "type": "boolean",
                  "name": "Alcohol",
                  "title": "Do you drink alcohol?"
                },
                {
                  "type": "text",
                  "name": "DrinksPerWeek",
                  "inputType": "number",
                  "visibleIf": "{Alcohol} = true",
                  "title": "How many drinks per week?"
                }
              ],
              "startWithNewLine": false
            },
            {
              "type": "panel",
              "name": "drug-use-history",
              "elements": [
                {
                  "type": "checkbox",
                  "name": "RecreationalDrugs",
                  "title": "Do you use recreational drugs?",
                  "choices": [
                    {
                      "value": "rarely",
                      "text": "Rarely"
                    },
                    {
                      "value": "marijuana",
                      "text": "Marijuana"
                    },
                    {
                      "value": "cocaine",
                      "text": "Cocaine"
                    },
                    {
                      "value": "opioids",
                      "text": "Opioids"
                    }
                  ],
                  "showOtherItem": true,
                  "otherPlaceholder": "Please specify... ",
                  "otherText": "Other",
                  "showNoneItem": true,
                  "noneText": "Never",
                  "colCount": 3
                },
                {
                  "type": "text",
                  "name": "DrugUseTimesPerMonth",
                  "visibleIf": "{RecreationalDrugs} anyof ['rarely', 'marijuana', 'cocaine', 'opioids', 'other']",
                  "title": "How many times per month",
                  "description": "If you take different types of drugs, please specify the frequency of use for each in a 'drug - # times/month' format."
                }
              ]
            },
            {
              "type": "panel",
              "name": "personal-info",
              "elements": [
                {
                  "type": "dropdown",
                  "name": "Education",
                  "title": "What is your highest level of education completed?",
                  "choices": [
                    {
                      "value": "high-school",
                      "text": "High School"
                    },
                    {
                      "value": "trade-school",
                      "text": "Trade School"
                    },
                    {
                      "value": "college",
                      "text": "College"
                    },
                    {
                      "value": "post-graduate",
                      "text": "Post-graduate degree(s)"
                    }
                  ]
                },
                {
                  "type": "dropdown",
                  "name": "MaritalStatus",
                  "title": "What is your marital status?",
                  "choices": [
                    {
                      "value": "married",
                      "text": "Married"
                    },
                    {
                      "value": "partnership",
                      "text": "Partnership"
                    },
                    {
                      "value": "divorced",
                      "text": "Divorced"
                    },
                    {
                      "value": "separated",
                      "text": "Separated"
                    },
                    {
                      "value": "single",
                      "text": "Single"
                    },
                    {
                      "value": "widow",
                      "text": "Widow(er)"
                    }
                  ]
                },
                {
                  "type": "panel",
                  "name": "sexual-life",
                  "elements": [
                    {
                      "type": "boolean",
                      "name": "SexuallyActive",
                      "title": "Are you sexually active?"
                    },
                    {
                      "type": "text",
                      "name": "SexualPartnersNumber",
                      "title": "How many sexual partners do you have?",
                      "inputType": "number",
                      "min": 0
                    },
                    {
                      "type": "radiogroup",
                      "name": "SexualPartnersGender",
                      "titleLocation": "hidden",
                      "choices": [
                        {
                          "value": "men",
                          "text": "Men"
                        },
                        {
                          "value": "women",
                          "text": "Women"
                        },
                        {
                          "value": "both",
                          "text": "Both"
                        }
                      ],
                      "colCount": 3
                    },
                    {
                      "type": "boolean",
                      "name": "Contraception",
                      "title": "Do you use contraception?"
                    },
                    {
                      "type": "comment",
                      "name": "ContraceptionComment",
                      "title": "What type of contraception do you use?",
                      "visibleIf": "{Contraception} = true"
                    }
                  ]
                }
              ]
            },
            {
              "type": "panel",
              "name": "employment-exercises-children",
              "startWithNewLine": false,
              "elements": [
                {
                  "type": "radiogroup",
                  "name": "Employment",
                  "title": "Are you employed?",
                  "choices": [
                    {
                      "value": "yes",
                      "text": "Yes"
                    },
                    {
                      "value": "no",
                      "text": "No"
                    },
                    {
                      "value": "retired",
                      "text": "Retired"
                    }
                  ],
                  "colCount": 3
                },
                {
                  "type": "comment",
                  "name": "EmploymentComment",
                  "title": "Type of work"
                },
                {
                  "type": "panel",
                  "name": "physical-activity",
                  "elements": [
                    {
                      "type": "boolean",
                      "name": "DoExercise",
                      "title": "Do you exercise?"
                    },
                    {
                      "type": "text",
                      "name": "ExerciseActivityType",
                      "title": "Type of activity",
                      "visibleIf": "{DoExercise} = true"
                    },
                    {
                      "type": "text",
                      "name": "ExerciseActivityFrequency",
                      "title": "How often?",
                      "visibleIf": "{DoExercise} = true"
                    },
                    {
                      "type": "text",
                      "name": "ExerciseActivityDuration",
                      "title": "How long per activity?",
                      "visibleIf": "{DoExercise} = true"
                    }
                  ]
                },
                {
                  "type": "panel",
                  "name": "children",
                  "elements": [
                    {
                      "type": "boolean",
                      "name": "HaveChildren",
                      "title": "Do you have children?"
                    },
                    {
                      "type": "text",
                      "name": "ChildrenNumber",
                      "title": "# of children",
                      "inputType": "number",
                      "visibleIf": "{HaveChildren} = true"
                    },
                    {
                      "type": "text",
                      "name": "ChildrenAges",
                      "title": "Their ages",
                      "visibleIf": "{HaveChildren} = true"
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "name": "SurgicalHistory",
      "title": "Surgical history / recent hospitalizations",
      "navigationTitle": "Surgical history",
      "elements": [
        {
          "type": "comment",
          "name": "SurgeryDescription",
          "title": "Date and type of surgery / procedure"
        }
      ]
    },
    {
      "name": "FamilyHistory",
      "title": "Family history",
      "navigationTitle": "Family history",
      "elements": [
        {
          "type": "matrixdynamic",
          "name": "FamilyHistory",
          "cellType": "text",
          "titleLocation": "hidden",
          "rowCount": 1,
          "columns": [
            {
              "name": "Relation"
            },
            {
              "name": "HealthConditions",
              "title": "Health conditions"
            },
            {
              "name": "CancerHistory",
              "title": "Family history of cancer"
            }
          ]
        }
      ]
    },
    {
      "name": "PreventiveCare",
      "title": "Preventive care",
      "navigationTitle": "Preventive care",
      "elements": [
        {
          "type": "panel",
          "name": "preventive-care",
          "elements": [
            {
              "type": "matrixdynamic",
              "name": "RecentShots",
              "title": "Recent shots from a doctor or pharmacist",
              "rowCount": 0,
              "columns": [
                {
                  "name": "Name",
                  "cellType": "dropdown",
                  "isRequired": true,
                  "choices": [
                    {
                      "value": "flu",
                      "text": "Flu"
                    },
                    {
                      "value": "shingles",
                      "text": "Shingles"
                    },
                    {
                      "value": "pneumonia",
                      "text": "Pneumonia"
                    },
                    {
                      "value": "tetanus",
                      "text": "Tetanus"
                    },
                    {
                      "value": "other",
                      "text": "Other"
                    }
                  ]
                },
                {
                  "name": "Date",
                  "cellType": "text",
                  "inputType": "date"
                },
                {
                  "name": "Place",
                  "cellType": "text"
                }
              ]
            },
            {
              "type": "matrixdynamic",
              "name": "RecentTests",
              "title": "Recent tests or procedures",
              "rowCount": 0,
              "columns": [
                {
                  "name": "Name",
                  "isRequired": true,
                  "cellType": "dropdown",
                  "choices": [
                    {
                      "value": "colonoscopy",
                      "text": "Colonoscopy"
                    },
                    {
                      "value": "cologuard",
                      "text": "Cologuard"
                    },
                    {
                      "value": "mammogram",
                      "text": "Mammogram"
                    },
                    {
                      "value": "pap",
                      "text": "PAP"
                    },
                    {
                      "value": "other",
                      "text": "Other"
                    }
                  ]
                },
                {
                  "name": "Date",
                  "cellType": "text",
                  "inputType": "date"
                },
                {
                  "name": "Place",
                  "cellType": "text"
                }
              ]
            },
            {
              "type": "matrixdynamic",
              "name": "Specialists",
              "cellType": "text",
              "columns": [
                {
                  "name": "Provider",
                  "title": "Provider's first and last name"
                },
                {
                  "name": "Speciality",
                  "title": "Speciality"
                },
                {
                  "name": "City",
                  "title": "Town/City"
                }
              ],
              "rowCount": 1
            },
            {
              "type": "matrixdynamic",
              "name": "Medications",
              "cellType": "text",
              "rowCount": 1,
              "columns": [
                {
                  "name": "Name"
                },
                {
                  "name": "Dose"
                },
                {
                  "name": "TimesPerDay",
                  "title": "Times per day"
                }
              ]
            },
            {
              "type": "matrixdynamic",
              "name": "Allergies",
              "cellType": "text",
              "rowCount": 1,
              "columns": [
                {
                  "name": "Type"
                },
                {
                  "name": "Reaction"
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "name": "Symptoms",
      "elements": [
        {
          "type": "tagbox",
          "name": "Symptoms",
          "title": "Please select any symptoms you have now or have had in the past month.",
          "choices": [
            "Fever",
            "Chills",
            "Feeling poorly",
            "Feeling tired",
            "Weight gain",
            "Weight loss",
            "Chest pain",
            "Heart pounding",
            "Fast pulse",
            "Slow pulse",
            "Leg pain with exercise",
            "Leg swelling",
            "Joint pain",
            "Neck pain",
            "Joint swelling",
            "Joint stiffness",
            "Muscle aches",
            "Back pain",
            "Sores",
            "Rash",
            "Itching",
            "Change in a mole",
            "Unusual growth/spot"
          ]
        },
        {
          "type": "text",
          "name": "CurrentDate",
          "title": "Today's date:",
          "titleLocation": "left",
          "inputType": "date",
          "defaultValueExpression": "today()"
        }
      ]
    }
  ],
  "showTOC": true,
  "completeText": "Submit",
  "showPreviewBeforeComplete": true,
  "widthMode": "static",
  "width": "1200px"
};
```

### `src/SurveyCreatorComponent.jsx`

```js
import React from "react";
import { SurveyCreator, SurveyCreatorComponent } from "survey-creator-react";
import "survey-core/survey.i18n";
import "survey-creator-core/survey-creator-core.i18n";
import { Serializer } from "survey-core";
import { ReactElementFactory } from "survey-react-ui";
import { formJSON } from "./survey_json";
import { generateDomainModelCode, isNameCorrect } from "./codegenerator";
import { Component } from "react";
import "survey-core/survey-core.css";
import "survey-creator-core/survey-creator-core.css";
import "./index.css";

import SurveyTheme from "survey-core/themes";
import { registerCreatorTheme } from "survey-creator-core";

registerCreatorTheme(SurveyTheme); // Add predefined Survey Creator UI themes

// Add the `name` property to the survey and limit the length for question and column names
Serializer.addProperty("survey", {
    name: "name",
    maxLength: 50,
    isRequired: true,
    category: "general",
    visibleIndex: 0
});
Serializer.findProperty("question", "name").maxLength = 50;
Serializer.findProperty("matrixdropdown", "name").maxLength = 50;


class TabServerCodeComponent extends Component {
    render() {
        const codeText = generateDomainModelCode(this.props.creator.survey);
        return React.createElement("textarea", { className: "generatortextarea", defaultValue: codeText });
    }
}

ReactElementFactory.Instance.registerElement(
    "svc-tab-servercode",
    (props) => {
        return React.createElement(TabServerCodeComponent, props);
    }
);

function SurveyCreatorRenderComponent() {
    const creator = new SurveyCreator();
    creator.onPropertyDisplayCustomError.add((_, options) => {
        if (options.propertyName !== "name") return;
        // Validate the `name` property for the survey, questions, and matrix columns
        if (options.element.isQuestion || ["survey", "matrixdropdowncolumn"].indexOf(options.element.getType()) > -1) {
            if (!isNameCorrect(options.value)) {
                options.error = "The current name cannot be used as a property in the server-side code. Please correct it.";
            }
        }
    });
    // An object that configures the behavior of the tab that displays server-side code.
    // No actions are performed when users select the tab (activate) or move away from it (deactivate).
    const templatesPlugin = {
        activate: () => { },
        deactivate: () => { return true; },
        model: creator
    };
    // Add the tab as a first tab to the Survey Creator
    creator.addTab({
        name: "servercode",
        plugin: templatesPlugin,
        title: "Domain Model Code",
        index: 0
    });
    creator.JSON = formJSON;
    
    return (<SurveyCreatorComponent creator={creator} />);
}

export default SurveyCreatorRenderComponent;
```

### `src/index.css`

```css
.generatortextarea {
    width: 100%;
    height: 100%;
    padding: 7px;
}
```

### `src/index.js`

```js
import React from "react";
import { createRoot } from "react-dom/client";
import SurveyCreatorRenderComponent from "./SurveyCreatorComponent";

const root = createRoot(document.getElementById("surveyCreatorContainer"));
root.render(<SurveyCreatorRenderComponent />);
```

### `package.json`

```json
{
  "dependencies": {
    "react": "latest",
    "react-dom": "latest",
    "survey-core": "latest",
    "survey-react-ui": "latest",
    "survey-creator-core": "latest",
    "survey-creator-react": "latest"
  },
  "devDependencies": {
    "react-scripts": "latest"
  }
}
```

## Other Frameworks

- [Angular](https://surveyjs.io/survey-creator/examples/create-domain-models/angular.md)
- [Vue 3](https://surveyjs.io/survey-creator/examples/create-domain-models/vue3js.md)
- [jQuery](https://surveyjs.io/survey-creator/examples/create-domain-models/jquery.md)
- [Vanilla JS](https://surveyjs.io/survey-creator/examples/create-domain-models/vanillajs.md)
