๐ŸŽฎ

Interactive Quiz

๐Ÿง‘โ€๐Ÿณ Cookโฑ๏ธ 25 minutes

๐Ÿ“‹ Suggested prerequisites

  • โ€ขBasic React
  • โ€ขuseState

What you'll build

An interactive quiz game with React. It will have questions with 4 options each, instant visual feedback (green for correct, red for incorrect), a score counter, and a results screen at the end. You'll learn to handle game flow, selection state, and conditional logic to create interactive experiences.


Step 1: Ask an AI for the quiz

I need an interactive quiz in React with:
- Array of questions with 4 options each
- Only one correct answer per question
- Visual feedback (green correct, red incorrect)
- Score counter
- Next question button
- Results screen at the end
- TypeScript and Tailwind CSS

Give me the complete code with 5 example questions.

Data structure

interface Question {
  id: number
  question: string
  options: string[]
  correctIndex: number
}

const questions: Question[] = [
  {
    id: 1,
    question: "What is the capital of France?",
    options: ["London", "Paris", "Madrid", "Rome"],
    correctIndex: 1
  },
  // more questions...
]

Quiz state

const [currentIndex, setCurrentIndex] = useState(0)
const [score, setScore] = useState(0)
const [selectedAnswer, setSelectedAnswer] = useState<number | null>(null)
const [showResult, setShowResult] = useState(false)

const currentQuestion = questions[currentIndex]

const handleAnswer = (index: number) => {
  setSelectedAnswer(index)
  if (index === currentQuestion.correctIndex) {
    setScore(score + 1)
  }
}

const nextQuestion = () => {
  if (currentIndex < questions.length - 1) {
    setCurrentIndex(currentIndex + 1)
    setSelectedAnswer(null)
  } else {
    setShowResult(true)
  }
}

Visual feedback

<button
  className={`p-3 rounded-lg ${
    selectedAnswer === index
      ? index === currentQuestion.correctIndex
        ? 'bg-green-500 text-white'
        : 'bg-red-500 text-white'
      : 'bg-gray-100 hover:bg-gray-200'
  }`}
  onClick={() => handleAnswer(index)}
  disabled={selectedAnswer !== null}
>
  {option}
</button>

Next step

โ†’ Timer with Notifications