”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 React 构建测验应用程序

使用 React 构建测验应用程序

发布于2024-11-01
浏览:571

Building a Quiz Application with React

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 (
    
Question : {currentQuestion 1} / {data.length}
Time left : {timer} seconds
); }; 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 (
    

{question}

{options.map((option, index) => ( ))} {showNextButton && }
); }; 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 logo from "./assets/images/quizlogo.png";
const App = () => {
  return (
    
logo

Made with ❤️ by Abhishek Gurjar

); }; 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 (
    

Quiz Complete

Your score is {score} out of {totalQuestion}

); } 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.

版本声明 本文转载于:https://dev.to/abhishekgurjar/building-a-quiz-application-with-react-3je9?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • Slim 和 Flight PHP 框架比较
    Slim 和 Flight PHP 框架比较
    为什么要使用微框架? 在社交媒体上,新的 PHP 开发人员经常会问“我的项目应该使用什么框架”,通常给出的答案是“Laravel”或“Symfony”。 虽然这些都是不错的选择,但这个问题的正确答案应该是“你需要框架做什么?” 正确的框架应该能够满足您的需要,并且不会包含大量您永远...
    编程 发布于2024-11-07
  • 如何构建您的第一个 Python 游戏:使用 PyGame 创建简单射击游戏的分步指南
    如何构建您的第一个 Python 游戏:使用 PyGame 创建简单射击游戏的分步指南
    Hi lovely readers, Have you ever wanted to create your own video game? Maybe you’ve thought about building a simple shooter game where you can move ar...
    编程 发布于2024-11-07
  • 为什么我的 Java JDBC 代码在连接到 Oracle 时抛出“IO 错误:网络适配器无法建立连接”?
    为什么我的 Java JDBC 代码在连接到 Oracle 时抛出“IO 错误:网络适配器无法建立连接”?
    诊断 Oracle JDBC“IO 错误:网络适配器无法建立连接”尝试使用 JDBC 执行简单的 Java 代码时要连接到 Oracle 数据库,您可能会遇到神秘的错误“IO 错误:网络适配器无法建立连接”。这个令人费解的消息源于 JDBC 驱动程序的模糊术语,并且可能由各种根本原因造成。以下是一些...
    编程 发布于2024-11-07
  • 如何使用 SwingPropertyChangeSupport 动态更新 JTextArea?
    如何使用 SwingPropertyChangeSupport 动态更新 JTextArea?
    使用 SwingPropertyChangeSupport 动态更新 JTextArea在此代码中,每当底层数据模型表示时,SwingPropertyChangeSupport 用于触发 JTextArea 中的更新通过 ArrayForUpdating 类进行更改。这允许动态更新 GUI 以响应数...
    编程 发布于2024-11-07
  • 如何将 Bootstrap 列中的内容居中?
    如何将 Bootstrap 列中的内容居中?
    Bootstrap 列中内容居中在 Bootstrap 中,可以通过多种方法实现列中内容居中。一常见的方法是在列 div 中使用align=“center”属性。例如:<div class="row"> <div class="col-xs-1&q...
    编程 发布于2024-11-07
  • 使用 Golang 进行身份验证、授权、MFA 等
    使用 Golang 进行身份验证、授权、MFA 等
    "Ó o cara falando de autenticação em pleno 2024!" Sim! Vamos explorar como realizar fluxos de autenticação e autorização, e de quebra, entender a dife...
    编程 发布于2024-11-07
  • 什么是“export default”以及它与“module.exports”有何不同?
    什么是“export default”以及它与“module.exports”有何不同?
    ES6 的“默认导出”解释JavaScript 的 ES6 模块系统引入了“默认导出”,这是一种定义默认导出的独特方式。 module.在提供的示例中,文件 SafeString.js 定义了一个 SafeString 类并将其导出为默认导出using:export default SafeStri...
    编程 发布于2024-11-07
  • SafeLine 如何通过高级动态保护保护您的网站
    SafeLine 如何通过高级动态保护保护您的网站
    SafeLine 由长亭科技在过去十年中开发,是一款最先进的 Web 应用程序防火墙 (WAF),它利用先进的语义分析算法来提供针对在线威胁的顶级保护。 SafeLine 在专业网络安全圈中享有盛誉并值得信赖,已成为保护网站安全的可靠选择。 SafeLine 社区版源自企业级 Ray Shield ...
    编程 发布于2024-11-07
  • 在 React 中创建自定义 Hook 的最佳技巧
    在 React 中创建自定义 Hook 的最佳技巧
    React 的自定义 Hooks 是从组件中删除可重用功能的有效工具。它们支持代码中的 DRY(不要重复)、可维护性和整洁性。但开发有用的自定义钩子需要牢牢掌握 React 的基本思想和推荐程序。在这篇文章中,我们将讨论在 React 中开发自定义钩子的一些最佳策略,并举例说明如何有效地应用它们。 ...
    编程 发布于2024-11-07
  • 如何解决 PHPMailer 中的 HTML 渲染问题?
    如何解决 PHPMailer 中的 HTML 渲染问题?
    PHPmailer的HTML渲染问题及其解决方法在PHPmailer中,当尝试发送HTML格式的电子邮件时,用户可能会遇到一个意想不到的问题:显示实际的HTML代码在电子邮件正文中而不是预期内容中。为了有效地解决这个问题,方法调用的特定顺序至关重要。正确的顺序包括在调用 isHTML() 方法之前设...
    编程 发布于2024-11-07
  • 通过 REST API 上的 GraphQL 增强 React 应用程序
    通过 REST API 上的 GraphQL 增强 React 应用程序
    In the rapidly changing world of web development, optimizing and scaling applications is always an issue. React.js had an extraordinary success for fr...
    编程 发布于2024-11-07
  • 为什么我的登录表单无法连接到我的数据库?
    为什么我的登录表单无法连接到我的数据库?
    登录表单的数据库连接问题尽管结合使用 PHP 和 MySQL 以及 HTML 和 Dreamweaver,您仍无法建立正确的数据库连接问题。登录表单和数据库之间的连接。缺少错误消息可能会产生误导,因为登录尝试仍然不成功。连接失败的原因:数据库凭据不正确: 确保用于连接数据库的主机名、数据库名称、用...
    编程 发布于2024-11-07
  • 为什么嵌套绝对定位会导致元素引用其父级而不是祖父母?
    为什么嵌套绝对定位会导致元素引用其父级而不是祖父母?
    嵌套定位:绝对内的绝对嵌套的绝对定位元素可能会在 CSS 中表现出意想不到的行为。考虑这种情况:第一个 div (#1st) 位置:相对第二个 div (#2nd) 相对于 #1st 绝对定位A第三个div(#3rd)绝对定位在#2nd内问:为什么#3rd相对于#2nd而不是#1st绝对定位?A: ...
    编程 发布于2024-11-07
  • 如何高效地从字符串中剥离特定文本?
    如何高效地从字符串中剥离特定文本?
    高效剥离字符串:如何删除特定文本片段遇到操作字符串值的需求是编程中的常见任务。经常面临的一项特殊挑战是删除特定文本片段,同时保留特定部分。在本文中,我们将深入研究此问题的实用解决方案。考虑这样一个场景,您有一个字符串“data-123”,您的目标是消除“data-”前缀,只留下“123”值。为了实现...
    编程 发布于2024-11-07
  • 如何将通讯录与手机同步?在 Go 中实现 CardDAV!
    如何将通讯录与手机同步?在 Go 中实现 CardDAV!
    假设您帮助管理一个小型组织或俱乐部,并拥有一个存储所有会员详细信息(姓名、电话、电子邮件...)的数据库。 在您需要的任何地方都可以访问这些最新信息不是很好吗?好吧,有了 CardDAV,你就可以! CardDAV 是一个得到良好支持的联系人管理开放标准;它在 iOS 联系人应用程序和许多适用于 A...
    编程 发布于2024-11-07

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3