Question T2789
Visible to All Users

Creating a question type as a React component

created 5 years ago

I want to create a new question type as a react component. I haven't found any examples so far.

Comments (1)
AP AP
Ankur Patankar 5 years ago

    If I wanted to write a custom widget is there boilerplate code I can use?

    Answers approved by surveyjs Support

    created 5 years ago

    Hello,

    This is the minimal working component sample:

    JavaScript
    import React from "react"; import * as Survey from "survey-react"; export class MyQuestionModel extends Survey.Question { constructor(name) { super(name); } getType() { return "myquestion"; } get text() { return this.getPropertyValue("text", ""); } set text(newValue) { this.setPropertyValue("text", newValue); } } export class MyQuestion extends Survey.SurveyElementBase { constructor(props) { super(props); } get question() { return this.props.question; } render() { if (!this.question) return null; var cssClasses = this.question.cssClasses; return ( <div className={cssClasses.root}> <span>My Text Value: </span><span><b>{this.question.text}</b></span> </div> ); } } Survey.Serializer.addClass( "myquestion", [ { name: "text" } ], function() { return new MyQuestionModel(""); }, "checkboxbase" ); Survey.ReactQuestionFactory.Instance.registerQuestion("myquestion", props => { return React.createElement(MyQuestion, props); });

    The question JSON is:

    JSON
    { "type": "myquestion", "name": "cq1", "text": "Some Text" }

    Thanks, Serge
    SurveyJS Team

      Comments (1)
      AP AP
      Ankur Patankar 5 years ago

        Thanks a lot. I will try to implement that.

        created 5 years ago

        Hello,

        Unfortunately we don't have such an example. You can use the https://github.com/surveyjs/survey-library/tree/master/src/react folder of our repo as a starting point, the https://github.com/surveyjs/survey-library/blob/master/src/react/imagepicker.tsx file. Note that SurveyJS Library is imlpemented for 3 platforms and that's why we have a platform-independent code - https://github.com/surveyjs/survey-library/blob/master/src/question_imagepicker.ts file in this case.
        In brief you need to create your own question/renderer and register it for using.

        Another (more easy) way to add a new question or customize an existing one is to create a custom widget (cross-platform vanilla JS code). Here is the repo - https://github.com/surveyjs/widgets and the live sample - https://plnkr.co/edit/HdnYE5?p=preview

        Thanks, Serge
        SurebyJS Team

          Comments (1)
          AP AP
          Ankur Patankar 5 years ago

            If I wanted to add a custom question what are the bare minimum necessities?

            class SomeCustomQuestion extends <???> {
            }