5.8. React: Sorting Question - Version 2

To follow along, open up the file questions/examples/SortingQuestion_v2/SortingQuestion_v2.jsx.

Looking at the code, there are only a few changes. First off, we require another shared component - the DefaultQuestionExplanation component.

To make use of it, we simply pass in the submitted state field - it takes care of the rest, including displaying the score, answer, and explanation. In addition, it will gracefully handle missing data by not showing those displays.

1

By default, the DefaultQuestionExplanation component will take the answer from the correct_answer field and the explanation from the explanation field.

This replaces the bulky code we had before; because all questions will have a score and maximum score, we can rely on it to display those. In addition, most questions will have an answer and explanation display. In fact, it would be a poorly-designed question if it didn’t have those fields!

Customizing the DefaultQuestionExplanation component

The fields used for the answer and explanation can be provided if they differ from the defaults by using the answerField and explanationField props, respectively.

For example, to select the answer from the field of actual_answer and the explanation from answer_explanation:

<DefaultQuestionExplanation data={this.state.submitted}
  answerField='actual_answer' explanationField='answer_explanation' />