I am creating a relatively basic website that provides a survey to users. But I've run into a dead end at the moment trying to figure a way to have the next question dependent on the answer to the previous question. So far I have a separate page holding an array of roughly 40 questions, a component that maps each question with its text and answer, and the page where they are rendered.
const questionArray = [
{
question: "how old are you?",
answers: [
"younger than 15",
"between 15 and 20",
"older than 20",
],
questionId: 1,
},
{
question: "are you a student?",
answers: ["yes", "no"],
questionId: 2,
},
{
question: "where do you live",
answers: ["QLD", "NSW", "VIC", "ACT", "NT", "TAS", "WA"],
questionId: 3,
},
];
const QuestionComponent = ({ question, options, selected }) => {
const [answer, setAnswer] = useState(options);
return (
<div>
{question}
{answer.map((text, index) => (
<button
key={index}
onClick={() => {
setAnswer([text]);
selected(text);
}}
>
{text}
</button>
))}
</div>
);
};
class QuestionPage extends Component {
state = {
questions: [],
};
getQs = () => {
this.setState({ questions: questionArray });
};
componentDidMount() {
this.getqs();
}
render() {
return (
<div>
{this.state.questions.map(
({ question, answers, questionId }) => (
<QuestionComponent
question={question}
options={answers}
key={questionId}
/>
),
)}
</div>
);
}
}
this method so far basically just lists all the questions through the component. I just can't work out how to go about changing it so as instead of listing all the questions initially, a question is added depending on the previous answer. For example, if the user answered question 1 with younger than 15 the next question would be question 3.
Any help would be greatly appreciated!