I have a form that contains several questions. Some of the questions are having a set of sub-questions. These are rendered using the following code.
{
Object.keys(this.props.moduleDetails.questions).map((questionInfo, index) => (
<div key={index}>
<QuestionAnswers
questionInfo={this.props.moduleDetails.questions[questionInfo]}
generateStepData={this.props.generateStepData}
states={this.props.states}
userEnteredValues={this.props.formValues}
errors={this.props.errors}
setQuestionAnswers={this.setQuestionAnswers}
/>
{this.props.moduleDetails.questions[questionInfo].question_group &&
this.props.moduleDetails.questions[questionInfo].has_grouped_questions ===
1 ? (
<div className="sub-questions">
{this.props.moduleDetails.questions[questionInfo].question_group ? (
<span>
{this.renderQuestionGroup(questionInfo)}
<input
type="button"
onClick={e => {
this.addQuestionGroup(questionInfo)
}}
value="Add"
className="btn"
/>
</span>
) : null}
</div>
) : null}
</div>
))
}
As you can see, the question groups are rendered using the renderQuestionGroup(questionInfo) method.
renderQuestionGroup(questionInfo) {
let input = [];
this.state.groupedQuestions[questionInfo] = (this.state.groupedQuestions[questionInfo]) ?
this.state.groupedQuestions[questionInfo]
: [];
let answerId = this.props.formValues[questionInfo];
let groupedQuestions = this.props.moduleDetails.questions[questionInfo].question_group[answerId];
if((groupedQuestions != null && this.state.groupedQuestions[questionInfo].length == 0) || this.state.isAddPressed) {
this.state.groupedQuestions[questionInfo].push(groupedQuestions);
}
input = this.display(questionInfo)
return input;
}
The problem here is that I cannot set state inside this method, as this method is called inside render method
Any idea on how to fix this?
Is there any alternate approach for this?