beginner#react#quiz#beginner
Creating a Simple Quiz Application with React
Learn how to create a simple quiz application using React, including setting up the questions and displaying the results.
Introduction to Quiz Application
In this tutorial, we will build a simple quiz application using React. This application will ask users a series of questions and display the results at the end.
Step 1: Setting up the Project
First, we need to set up a new React project. We can do this by running the following command in our terminal:
npx create-react-app quiz-app
Step 2: Creating the Quiz Component
Next, we need to create a new component for our quiz application. We can do this by creating a new file called Quiz.js in the src directory:
import React, { useState } from 'react';
function Quiz() {
const [questions, setQuestions] = useState([
{ question: 'What is the capital of France?', answer: 'Paris' },
{ question: 'What is the largest planet in our solar system?', answer: 'Jupiter' },
{ question: 'Who painted the Mona Lisa?', answer: 'Leonardo da Vinci' }
]);
const [currentQuestion, setCurrentQuestion] = useState(0);
const [score, setScore] = useState(0);
const [userAnswer, setUserAnswer] = useState('');
const handleNextQuestion = () => {
if (userAnswer === questions[currentQuestion].answer) {
setScore(score + 1);
}
setCurrentQuestion(currentQuestion + 1);
setUserAnswer('');
};
return (
<div>
{currentQuestion < questions.length ? (
<div>
<p>{questions[currentQuestion].question}</p>
<input type='text' value={userAnswer} onChange={(e) => setUserAnswer(e.target.value)} />
<button onClick={handleNextQuestion}>Next</button>
</div>
) : (
<div>
<p>Quiz finished! Your score is {score} out of {questions.length}.</p>
</div>
)}
</div>
);
}
export default Quiz;