Introduction
In this tutorial, we will walk you through building a fun and interactive Quiz Website using React. This project is a great way for beginners to practice handling user input, managing state, and rendering dynamic content in React.
Project Overview
The Quiz Website allows users to answer multiple-choice questions and get instant feedback on their selections. At the end of the quiz, users are shown their scores along with the correct answers.
Features
- Interactive Quiz: Users can answer questions and see their scores.
- Real-Time Feedback: Immediate indication of whether the selected answer is correct or not.
- Score Calculation: Keeps track of the score throughout the quiz.
- Dynamic Content: Questions and options are rendered dynamically from a predefined list.
Technologies Used
- React: For building the user interface and managing component states.
- CSS: For styling the application.
- JavaScript: For handling logic and quiz functionality.
Project Structure
The project is structured as follows:
├── public ├── src │ ├── components │ │ ├── Quiz.jsx │ │ ├── Question.jsx │ ├── App.jsx │ ├── App.css │ ├── index.js │ └── index.css ├── package.json └── README.md
Key Components
- Quiz.jsx: Handles the quiz logic and score calculation.
- Question.jsx: Displays individual questions and handles user input.
- App.jsx: Manages the layout and renders the Quiz component.
Code Explanation
Quiz Component
The Quiz component is responsible for rendering the questions, calculating the score, and handling quiz completion.
import { useEffect, useState } from "react"; import Result from "./Result"; import Question from "./Question"; const data = [ { question: "What is the capital of France?", options: ["Paris", "Berlin", "Madrid", "Rome"], answer: "Paris", }, { question: "What is the capital of Germany?", options: ["Berlin", "Munich", "Frankfurt", "Hamburg"], answer: "Berlin", }, { question: "What is the capital of Spain?", options: ["Madrid", "Barcelona", "Seville", "Valencia"], answer: "Madrid", }, { question: "What is the capital of Italy?", options: ["Rome", "Milan", "Naples", "Turin"], answer: "Rome", }, { question: "What is the capital of the United Kingdom?", options: ["London", "Manchester", "Liverpool", "Birmingham"], answer: "London", }, { question: "What is the capital of Canada?", options: ["Ottawa", "Toronto", "Vancouver", "Montreal"], answer: "Ottawa", }, { question: "What is the capital of Australia?", options: ["Canberra", "Sydney", "Melbourne", "Brisbane"], answer: "Canberra", }, { question: "What is the capital of Japan?", options: ["Tokyo", "Osaka", "Kyoto", "Nagoya"], answer: "Tokyo", }, { question: "What is the capital of China?", options: ["Beijing", "Shanghai", "Guangzhou", "Shenzhen"], answer: "Beijing", }, { question: "What is the capital of Russia?", options: ["Moscow", "Saint Petersburg", "Novosibirsk", "Yekaterinburg"], answer: "Moscow", }, { question: "What is the capital of India?", options: ["New Delhi", "Mumbai", "Bangalore", "Chennai"], answer: "New Delhi", }, { question: "What is the capital of Brazil?", options: ["Brasilia", "Rio de Janeiro", "Sao Paulo", "Salvador"], answer: "Brasilia", }, { question: "What is the capital of Mexico?", options: ["Mexico City", "Guadalajara", "Monterrey", "Tijuana"], answer: "Mexico City", }, { question: "What is the capital of South Africa?", options: ["Pretoria", "Johannesburg", "Cape Town", "Durban"], answer: "Pretoria", }, { question: "What is the capital of Egypt?", options: ["Cairo", "Alexandria", "Giza", "Luxor"], answer: "Cairo", }, { question: "What is the capital of Turkey?", options: ["Ankara", "Istanbul", "Izmir", "Antalya"], answer: "Ankara", }, { question: "What is the capital of Argentina?", options: ["Buenos Aires", "Cordoba", "Rosario", "Mendoza"], answer: "Buenos Aires", }, { question: "What is the capital of Nigeria?", options: ["Abuja", "Lagos", "Kano", "Ibadan"], answer: "Abuja", }, { question: "What is the capital of Saudi Arabia?", options: ["Riyadh", "Jeddah", "Mecca", "Medina"], answer: "Riyadh", }, { question: "What is the capital of Indonesia?", options: ["Jakarta", "Surabaya", "Bandung", "Medan"], answer: "Jakarta", }, { question: "What is the capital of Thailand?", options: ["Bangkok", "Chiang Mai", "Phuket", "Pattaya"], answer: "Bangkok", }, { question: "What is the capital of Malaysia?", options: ["Kuala Lumpur", "George Town", "Johor Bahru", "Malacca"], answer: "Kuala Lumpur", }, { question: "What is the capital of the Philippines?", options: ["Manila", "Cebu City", "Davao City", "Quezon City"], answer: "Manila", }, { question: "What is the capital of Vietnam?", options: ["Hanoi", "Ho Chi Minh City", "Da Nang", "Hai Phong"], answer: "Hanoi", }, { question: "What is the capital of South Korea?", options: ["Seoul", "Busan", "Incheon", "Daegu"], answer: "Seoul", }, ]; const Quiz = () => { const [currentQuestion, setCurrentQuestion] = useState(0); const [score, setScore] = useState(0); const [showResult, setShowResult] = useState(false); const [timer, setTimer] = useState(30); const [showNextButton, setShowNextButton] = useState(true); useEffect(() => { if (timer === 0) { handleNext(); } const timerId = setTimeout(() => setTimer(timer - 1), 1000); return () => clearTimeout(timerId); }, [timer]); const handleAnswer = (selectedOption) => { if (selectedOption === data[currentQuestion].answer) { setScore(score + 1); } setShowNextButton(true); // Show the next button after answering }; const handleNext = () => { const nextQuestion = currentQuestion + 1; if (nextQuestion ; } return ( <div classname="quiz"> <div classname="countandTime"> <div classname="questionNumber"> Question : {currentQuestion + 1} <b>/</b> {data.length} </div> <div classname="timer">Time left : {timer} seconds</div> </div> <question question="{data[currentQuestion].question}" options="{data[currentQuestion].options}" onanswer="{handleAnswer}" onnext="{handleNext}" shownextbutton="{showNextButton}"></question> </div> ); }; export default Quiz;
The Quiz component manages the current question index and score. It also tracks when the quiz is finished, displaying the final score once all questions are answered.
Question Component
The Question component handles the display of each question and allows the user to select an answer.
const Question = ({ question, options, onAnswer, onNext, showNextButton }) => { return ( <div classname="question"> <h2 id="question">{question}</h2> {options.map((option, index) => ( <button classname="option" key="{index}" onclick="{()"> onAnswer(option)}> {option} </button> ))} {showNextButton && <button classname="next" onclick="{onNext}">Next </button>} </div> ); }; export default Question;
This component takes the data prop, which includes the question and its options, and renders it dynamically. The handleAnswer function processes the selected option.
App Component
The App component manages the layout and renders the Quiz component.
import Quiz from "./components/Quiz"; import "./App.css"; import Building a Quiz Application with React from "./assets/images/quizBuilding a Quiz Application with React.png"; const App = () => { return ( <div classname="app"> <img classname="Building a Quiz Application with React" src="%7BBuilding" a quiz application with react alt="Building a Quiz Application with React"> <quiz></quiz> <p classname="footer">Made with ❤️ by Abhishek Gurjar</p> </div> ); }; export default App;
This component structures the page with a header and footer, and the Quiz component is rendered in the center.
Result Component
The Result component is responsible for showing the user's quiz score after they submit their answers. It calculates the score by comparing the user's responses with the correct answers and provides feedback on how many questions were answered correctly.
const Result = ({ score, totalQuestion }) => { return ( <div classname="result"> <h2 id="Quiz-Complete">Quiz Complete</h2> <p>Your score is {score} out of {totalQuestion}</p> </div> ); } export default Result;
In this component, the score and total number of questions are passed as props. Based on the score, the component displays a message to the user, either praising them for getting all the answers correct or encouraging them to keep practicing. This dynamic feedback helps users understand their performance.
CSS Styling
The CSS ensures a clean and simple layout for the quiz. It styles the quiz components and provides user-friendly visuals.
* { box-sizing: border-box; } body { background-color: #cce2c2; color: black; margin: 0; padding: 0; font-family: sans-serif; } .app { width: 100%; display: flex; align-items: center; justify-content: flex-start; flex-direction: column; } .app img { margin: 50px; } /* Quiz */ .quiz { display: flex; flex-direction: column; align-items: center; width: 60%; margin: 0 auto; } .countandTime { display: flex; align-items: center; gap: 300px; } .questionNumber { font-size: 20px; background-color: #fec33d; padding: 10px; border-radius: 10px; font-weight: bold; } .timer { font-size: 18px; background-color: #44b845; color: white; padding: 10px; border-radius: 10px; font-weight: bold; } /* Question */ .question { margin-top: 20px; } .question h2 { background-color: #eaf0e7; width: 690px; padding: 30px; border-radius: 10px; } .question .option { display: flex; margin-block: 20px; flex-direction: column; align-items: flex-start; background-color: #eaf0e7; padding: 20px; border-radius: 10px; font-size: 18px; width: 690px; } .question .next { font-size: 25px; color: white; background-color: #35bd3a; border: none; padding: 10px; width: 100px; border-radius: 10px; margin-left: 590px; } /* Result */ .result { border-radius: 19px; display: flex; align-items: center; justify-content: center; flex-direction: column; width: 500px; height: 300px; margin-top: 140px; background-color: #35bd3a; color: white; } .result h2{ font-size: 40px; } .result p{ font-size: 25px; } .footer { margin: 40px; }
The styling ensures that the layout is centered and provides hover effects on the quiz options, making it more interactive.
Installation and Usage
To get started with this project, clone the repository and install the dependencies:
git clone https://github.com/abhishekgurjar-in/quiz-website.git cd quiz-website npm install npm start
This will start the development server, and the application will be running at http://localhost:3000.
Live Demo
Check out the live demo of the Quiz Website here.
Conclusion
This Quiz Website is an excellent project for beginners looking to enhance their React skills. It provides an engaging way to practice managing state, rendering dynamic content, and handling user input.
Credits
- Inspiration: The project is inspired by the classic quiz games, combining fun and learning.
Author
Abhishek Gurjar is a web developer passionate about building interactive and engaging web applications. You can follow his work on GitHub.
The above is the detailed content of Building a Quiz Application with React. For more information, please follow other related articles on the PHP Chinese website!

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
