I have the following React.js component where I get 10 multiple-choice trivia questions via an API call using fetch and recursively list them on the page via nested components.
The API provides 'correct_answer' as string, and 'incorrect_answers' separately as an array of strings. In my current code, I am only able to list the 'correct' and 'incorrect' answers in their own components.
What I would like to do is combine the 'correct' and 'incorrect' answers into a single array and then randomise the output of them, so that the correct answer is not always in the same place in the list. How would I alter my current code to that? I am an absolute beginner at React.js so any pointers are welcome, thanks.
import React, { Component } from "react";
class QuestionContainer extends Component {
constructor() {
super();
this.state = {
questions: []
};
}
componentWillMount() {
const RenderHTMLQuestion = (props) => (<p dangerouslySetInnerHTML={{__html:props.HTML}}></p>)
const RenderHTMLAnswer = (props) => (<li dangerouslySetInnerHTML={{__html:props.HTML}}></li>)
fetch('https://opentdb.com/api.php?amount=10&category=9&type=multiple')
.then(results => {
return results.json();
}).then(data => {
let questions = data.results.map((question, index) => {
return(
<div key={index} className="questionWrapper">
<div className="question" key={question.question}>
<RenderHTMLQuestion HTML={question.question} />
</div>
<ul className="answers">
<RenderHTMLAnswer key={question.correct_answer} HTML={question.correct_answer} />
{question.incorrect_answers.map((answer, index) => (
<RenderHTMLAnswer key={index} HTML={answer} />
))}
</ul>
</div>
)
})
this.setState({questions: questions});
})
}
render() {
return (
<div className="container2">
{this.state.questions}
</div>
)
}
}
export default QuestionContainer;