」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 React 建立測驗應用程式

使用 React 建立測驗應用程式

發佈於2024-11-01
瀏覽:755

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 用於觸發JTextArea 中的更新透過ArrayForUpdating 類別進行更改。這允許動...
    程式設計 發佈於2024-11-07
  • 如何將 Bootstrap 欄位中的內容置中?
    如何將 Bootstrap 欄位中的內容置中?
    Bootstrap 列中內容居中在 Bootstrap 中,可以透過多種方法實現列中內容居中。 一常見的方法是在列 div 中使用align=“center”屬性。例如:<div class="row"> <div class="col-xs-1&...
    程式設計 發佈於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 類,並將其匯出為預設匯出,使用:export default SafeString;此...
    程式設計 發佈於2024-11-07
  • SafeLine 如何透過進階動態保護來保護您的網站
    SafeLine 如何透過進階動態保護來保護您的網站
    SafeLine 由長亭科技在過去十年中開發,是一款最先進的 Web 應用程式防火牆 (WAF),它利用先進的語義分析演算法來提供針對線上威脅的頂級保護。 SafeLine 在專業網路安全圈中享有盛譽並值得信賴,已成為保護網站安全的可靠選擇。 SafeLine 社群版源自企業級 Ray Shiel...
    程式設計 發佈於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