Hi Developer! Today in this article, I will give you the best technique for creating a quiz app by using React without installing other libraries.
In this article, we have walked you through each step of building a quiz application using React with code examples, providing both educational value and practical experience. We are confident that, by the end of this article, you will be able to create a great quiz app.
So let's get started.
Prerequisites to Make a Quiz App in React
- Familiarity with ReactJS:
- Knowledge of React Hooks:
- Knowledge of React Props:
- Knowledge of React Components:
How can we build logic for this quiz app?
When you're making a quiz app, you need to think about how it's going to work. Like, how are we going to show the questions? And how will people answer them? Also, we need to know whether the answer given by the user is right or wrong. So, we need to plan it out well to make sure it runs nice and smoothly. Let's break it down into simple steps, so our Quiz App is super easy for everyone to use.
Create a quiz app step-by-step
Step 1: Set Up Your React Project
First, let's set up a new React project using the Create React App. Open your terminal and run the following commands:
npx create-react-app quiz-app
cd quiz-app
This will create a new React project named quiz-app and navigate you into its directory.
Step 2: Structure Your Project
First, create two new files named Quiz.jsx and Question.jsx within your components folder located in the src directory. Next, create a question.json file within your data folder, also located in the src directory.
Step 3: Create Quiz Data
Define the quiz questions by utilizing a questions.json file located within the data folder.
[
{
"question": "What is React?",
"options": [
"A database management system",
"A programming language",
"A JavaScript library for building user interfaces ",
"A web browser"
],
"answer": "A JavaScript library for building user interfaces "
},
{
"question": "What is the purpose of a constructor in JavaScript?",
"options": [
"To style HTML elements",
"To initialize an object's properties",
"To create a new database table",
"To fetch data from an API"
],
"answer": "To initialize an object's properties"
},
{
"question": "What does DOM stand for in JavaScript?",
"options": [
"Document Object Model",
"Database Object Model",
"Document Oriented Model",
"Data Object Model"
],
"answer": "Document Object Model"
}
]
This JSON data holds a series of quiz questions stored in a format that's easy to work with. Each question comes with its own details:
- "question": It holds the question that users will see and try to answer.
- "options": This array lists the different choices users can pick from as their answer.
- "answer": This specifies which option is the correct answer to the question.
Step 4: Get question data and build logic
Include the following code in the Question.jsx file:
// Question.jsx
import React from 'react';
const Question = ({ question, options, onSelect }) => {
return (
<div>
<h3>{question}</h3>
<div className="options">
{options.map(option => (
<button key={option} onClick={() => onSelect(option)}>{option}</button>
))}
</div>
</div>
);
};
export default Question;
This code represents a component in React named "Question". It's like a building block used to create a quiz app. Here's what it does:
- It takes three things: the question itself ("question"), the possible answers ("options"), and a way to handle when a user selects an answer ("onSelect").
- When you use this component, it shows the question and a bunch of buttons, each with one of the possible answers.
- When a user clicks on a button, the "onSelect" function is triggered. It helps the app know which answer the user picked.
Quiz.jsx file:
// Quiz.jsx
import React, { useEffect, useState } from 'react';
import Question from './Question';
import questionsData from '../data/question.json';
const Quiz = () => {
// State variables to manage quiz progress and completion
const [currentQuestion, setCurrentQuestion] = useState(0);
const [score, setScore] = useState(0);
const [quizCompleted, setQuizCompleted] = useState(false);
const [completionMessage, setCompletionMessage] = useState('');
// Function to handle user's answer selection
const handleAnswerSelect = (selectedOption) => {
const currentAnswer = questionsData[currentQuestion].answer;
if (selectedOption === currentAnswer) {
setScore(score + 1);
}
const nextQuestion = currentQuestion + 1;
if (nextQuestion < questionsData.length) {
setCurrentQuestion(nextQuestion);
} else {
setQuizCompleted(true);
}
};
// Effect to determine completion message whenever score changes
useEffect(() => {
determineCompletionMessage(score);
}, [score]);
// Function to determine completion message based on score
const determineCompletionMessage = (currentScore) => {
const totalQuestions = questionsData.length;
if (currentScore === 0) {
setCompletionMessage(`Oops, you scored ${currentScore}/${totalQuestions}. You are wrong.`);
} else if (currentScore === totalQuestions) {
setCompletionMessage(`🎉Congratulations! You scored ${currentScore}/${totalQuestions}. You did well.`);
} else {
setCompletionMessage(`Good, but you scored ${currentScore}/${totalQuestions}. Do some more practice.`);
}
};
// Function to restart the quiz
const handleRestartQuiz = () => {
setCurrentQuestion(0);
setScore(0);
setQuizCompleted(false);
setCompletionMessage('');
};
// JSX to render quiz components based on quiz state
return (
<div className="quiz-container">
<h1>Quiz App</h1>
{!quizCompleted ? (
<>
<Question
question={questionsData[currentQuestion].question}
options={questionsData[currentQuestion].options}
onSelect={handleAnswerSelect}
/>
<div className="score">Score: {score}/{questionsData.length}</div>
</>
) : (
<div className="quiz-completed fade-in">
<h2>Quiz Completed!</h2>
<p>{completionMessage}</p>
<button onClick={handleRestartQuiz}>Restart Quiz</button>
</div>
)}
</div>
);
};
export default Quiz;
The 'Quiz' React component is important for making a quiz app. Let's dive into its features!
- State Management: The component efficiently tracks the quiz's progress, including the current question, the user's score, and completion status.
- Answer Selection: Through the "handleAnswerSelect" function, users can select answers. If correct, the score updates accordingly, and the quiz progresses to the next question.
- useEffect: In this case, useEffect makes sure the completion message always shows the right score. So, whenever the user's score changes, the message updates too. That way, users get the latest and most accurate feedback.
- Completion Message: A dynamic completion message is generated based on the user's score. After finishing the quiz, it lets users know how they did, so they understand their performance! It's like feedback.
- Restart Capability: Users have the option to restart the quiz once completed, allowing for additional attempts. This functionality resets all progress, providing a fresh start.
- Rendering Logic: The component dynamically renders quiz questions and options based on the current state. When the quiz is completed, a message displays along with an option to restart, ensuring a seamless user experience.
Step 5: Integrate the quiz Component
Open App.js and replace its content with the following:
// App.js
import React from 'react';
import './App.css';
import Quiz from './components/Quiz'
function App() {
return (
<div className="App">
<Quiz />
</div>
);
}
export default App;
This code initializes a React application by rendering the "Quiz" component within a div with the class "App", styling applied from an external CSS file.
You can add this code in the App.css file for UI design.
body {
font-family: sans-serif;
background-color: steelblue;
color: white;
}
.quiz-container {
border: 5px solid rgb(106, 162, 207);
border-radius: 5px;
max-width: 600px;
margin: 200px auto;
padding: 20px 50px;
}
.options {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 10px;
}
button {
padding: 10px;
border-radius: 5px;
background-color: rgb(37, 37, 37);
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: black
}
.score {
margin-top: 20px;
font-size: 18px;
}
.quiz-completed {
text-align: center;
}
.quiz-completed button {
margin-top: 20px;
}
.quiz-completed {
text-align: center;
opacity: 0;
}
.fade-in {
animation: fadeInAnimation 1s ease-in forwards;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
Step 6: Run Your Application
Now, let's test our quiz app. Go to the project folder (quiz-app) in the terminal and type the command to run it.
npm start
Good! We have built a quiz app using React that works well. You can make it even better. So go ahead and make it even better and increase your skills.
Conclusion
Building the quiz app while learning React improves our React development experience. By following all of the steps listed in this guide, you will have created an excellent quiz app. To further increase user engagement, you can add more functionality to this project, such as timer functionality, difficulty levels, or a multiplayer option, which will also boost your skills.
If you have any questions regarding this article or any other web development, then you can ask them in the question box given below, and you will get an answer soon.