JSFiddle - React, Tailwind, and code Playground
HTML
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>
Babel + JSX
const { useState, useEffect } = React;
function Question({ question, answer, onAnswerChange }) {
const onChange = e => onAnswerChange(+e.target.value);
return (
<div>
<h3>{question.text}</h3>
<ul>{question.answers.map((n, i) => (
<li>
<label>
<input type="radio" value={i} checked={answer === i} onChange={onChange} />
{n}
</label>
</li>))}
</ul>
</div>
);
}
function Results({ questions, answers }) {
const correctAnswers = questions.reduce((acc, n, i) => {
if (answers[i] === n.correctAnswer) {
acc.push(`${n.text} - ${n.answers[n.correctAnswer]}`);
}
return acc;
}, []);
return (
<div>
<h3>Результаты</h3>
<div>Верных ответов - {correctAnswers.length}</div>
<ul>
{correctAnswers.map(n => <li>{n}</li>)}
</ul>
</div>
);
}
function Quiz({ questions }) {
const [ answers, setAnswers ] = useState([]);
const [ iQuestion, setIQuestion ] = useState(-1);
const question = questions[iQuestion];
const answer = answers[iQuestion];
const nextQuestion = ({ target: { dataset: { step } } }) =>
setIQuestion(iQuestion + +step);
const updateAnswer = (answer) =>
setAnswers(answers.map((n, i) => i === iQuestion ? answer : n));
const start = () => {
setAnswers(Array(questions.length).fill(null));
setIQuestion(0);
};
useEffect(start, []);
return (
<div>
{question && <>
<Question question={question} answer={answer} onAnswerChange={updateAnswer} />
<button onClick={nextQuestion} data-step="-1" disabled={iQuestion === 0}>Назад</button>
<button onClick={nextQuestion} data-step="+1" disabled={answer === null}>Дальше</button>
</>}
{iQuestion === questions.length && <>
<Results questions={questions} answers={answers} />
<button onClick={start}>Начать заново</button>
</>}
</div>
);
}
const questions = [
{
text: 'Выберите...