How to Build a Quiz App with React: A Step‑by‑Step Tutorial
React’s component‑based architecture makes building interactive apps like a quiz straightforward. You’ll manage state, handle user input, and dynamically render questions – all with clean, reusable code. This tutorial walks through the core steps using functional components and hooks.
1. Set Up the Project
Start by creating a new React app with npx create-react-app quiz-app or vite. Inside src/, remove boilerplate files and create a folder components. You’ll only need a few files: App.js, Quiz.js, and a data file for questions.
2. Define Question Data and State
Create a questions.js array with objects containing question, options, and correctAnswer. In Quiz.js, use useState to track:
- currentQuestion (index)
- score (number of correct answers)
- showResults (boolean)
3. Render Questions and Handle Answers
Display the current question and its options as clickable buttons. On each click, compare the selected option with correctAnswer. Update score if correct, then move to the next question:
const handleAnswer = (selected) => {
if (selected === questions[currentQuestion].correctAnswer)
setScore(score + 1);
// handle last question
if (currentQuestion + 1 < questions.length)
setCurrentQuestion(currentQuestion + 1);
else
setShowResults(true);
};
4. Display Results
When showResults is true, render a component that shows the final score and a “Restart” button. The restart button resets all state back to initial values.
Conclusion
With just a few hooks and some conditional rendering, you have a functional quiz app. Enhance it by adding animations, a timer, or multiple categories. React’s flexibility makes expansion effortless.